socket.io.js 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747
  1. /*!
  2. * Socket.IO v4.6.2
  3. * (c) 2014-2023 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 = globalThisShim.setTimeout;
  562. var NATIVE_CLEAR_TIMEOUT = globalThisShim.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 = globalThisShim.setTimeout.bind(globalThisShim);
  569. obj.clearTimeoutFn = globalThisShim.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} opts - options
  618. * @protected
  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.socket = opts.socket;
  629. return _this2;
  630. }
  631. /**
  632. * Emits an error.
  633. *
  634. * @param {String} reason
  635. * @param description
  636. * @param context - the error context
  637. * @return {Transport} for chaining
  638. * @protected
  639. */
  640. _createClass(Transport, [{
  641. key: "onError",
  642. value: function onError(reason, description, context) {
  643. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "error", new TransportError(reason, description, context));
  644. return this;
  645. }
  646. /**
  647. * Opens the transport.
  648. */
  649. }, {
  650. key: "open",
  651. value: function open() {
  652. this.readyState = "opening";
  653. this.doOpen();
  654. return this;
  655. }
  656. /**
  657. * Closes the transport.
  658. */
  659. }, {
  660. key: "close",
  661. value: function close() {
  662. if (this.readyState === "opening" || this.readyState === "open") {
  663. this.doClose();
  664. this.onClose();
  665. }
  666. return this;
  667. }
  668. /**
  669. * Sends multiple packets.
  670. *
  671. * @param {Array} packets
  672. */
  673. }, {
  674. key: "send",
  675. value: function send(packets) {
  676. if (this.readyState === "open") {
  677. this.write(packets);
  678. }
  679. }
  680. /**
  681. * Called upon open
  682. *
  683. * @protected
  684. */
  685. }, {
  686. key: "onOpen",
  687. value: function onOpen() {
  688. this.readyState = "open";
  689. this.writable = true;
  690. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "open");
  691. }
  692. /**
  693. * Called with data.
  694. *
  695. * @param {String} data
  696. * @protected
  697. */
  698. }, {
  699. key: "onData",
  700. value: function onData(data) {
  701. var packet = decodePacket(data, this.socket.binaryType);
  702. this.onPacket(packet);
  703. }
  704. /**
  705. * Called with a decoded packet.
  706. *
  707. * @protected
  708. */
  709. }, {
  710. key: "onPacket",
  711. value: function onPacket(packet) {
  712. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "packet", packet);
  713. }
  714. /**
  715. * Called upon close.
  716. *
  717. * @protected
  718. */
  719. }, {
  720. key: "onClose",
  721. value: function onClose(details) {
  722. this.readyState = "closed";
  723. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "close", details);
  724. }
  725. /**
  726. * Pauses the transport, in order not to lose packets during an upgrade.
  727. *
  728. * @param onPause
  729. */
  730. }, {
  731. key: "pause",
  732. value: function pause(onPause) {}
  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. * @package
  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. _createClass(Polling, [{
  867. key: "name",
  868. get: function get() {
  869. return "polling";
  870. }
  871. /**
  872. * Opens the socket (triggers polling). We write a PING message to determine
  873. * when the transport is open.
  874. *
  875. * @protected
  876. */
  877. }, {
  878. key: "doOpen",
  879. value: function doOpen() {
  880. this.poll();
  881. }
  882. /**
  883. * Pauses polling.
  884. *
  885. * @param {Function} onPause - callback upon buffers are flushed and transport is paused
  886. * @package
  887. */
  888. }, {
  889. key: "pause",
  890. value: function pause(onPause) {
  891. var _this2 = this;
  892. this.readyState = "pausing";
  893. var pause = function pause() {
  894. _this2.readyState = "paused";
  895. onPause();
  896. };
  897. if (this.polling || !this.writable) {
  898. var total = 0;
  899. if (this.polling) {
  900. total++;
  901. this.once("pollComplete", function () {
  902. --total || pause();
  903. });
  904. }
  905. if (!this.writable) {
  906. total++;
  907. this.once("drain", function () {
  908. --total || pause();
  909. });
  910. }
  911. } else {
  912. pause();
  913. }
  914. }
  915. /**
  916. * Starts polling cycle.
  917. *
  918. * @private
  919. */
  920. }, {
  921. key: "poll",
  922. value: function poll() {
  923. this.polling = true;
  924. this.doPoll();
  925. this.emitReserved("poll");
  926. }
  927. /**
  928. * Overloads onData to detect payloads.
  929. *
  930. * @protected
  931. */
  932. }, {
  933. key: "onData",
  934. value: function onData(data) {
  935. var _this3 = this;
  936. var callback = function callback(packet) {
  937. // if its the first message we consider the transport open
  938. if ("opening" === _this3.readyState && packet.type === "open") {
  939. _this3.onOpen();
  940. } // if its a close packet, we close the ongoing requests
  941. if ("close" === packet.type) {
  942. _this3.onClose({
  943. description: "transport closed by the server"
  944. });
  945. return false;
  946. } // otherwise bypass onData and handle the message
  947. _this3.onPacket(packet);
  948. }; // decode payload
  949. decodePayload(data, this.socket.binaryType).forEach(callback); // if an event did not trigger closing
  950. if ("closed" !== this.readyState) {
  951. // if we got data we're not polling
  952. this.polling = false;
  953. this.emitReserved("pollComplete");
  954. if ("open" === this.readyState) {
  955. this.poll();
  956. }
  957. }
  958. }
  959. /**
  960. * For polling, send a close packet.
  961. *
  962. * @protected
  963. */
  964. }, {
  965. key: "doClose",
  966. value: function doClose() {
  967. var _this4 = this;
  968. var close = function close() {
  969. _this4.write([{
  970. type: "close"
  971. }]);
  972. };
  973. if ("open" === this.readyState) {
  974. close();
  975. } else {
  976. // in case we're trying to close while
  977. // handshaking is in progress (GH-164)
  978. this.once("open", close);
  979. }
  980. }
  981. /**
  982. * Writes a packets payload.
  983. *
  984. * @param {Array} packets - data packets
  985. * @protected
  986. */
  987. }, {
  988. key: "write",
  989. value: function write(packets) {
  990. var _this5 = this;
  991. this.writable = false;
  992. encodePayload(packets, function (data) {
  993. _this5.doWrite(data, function () {
  994. _this5.writable = true;
  995. _this5.emitReserved("drain");
  996. });
  997. });
  998. }
  999. /**
  1000. * Generates uri for connection.
  1001. *
  1002. * @private
  1003. */
  1004. }, {
  1005. key: "uri",
  1006. value: function uri() {
  1007. var query = this.query || {};
  1008. var schema = this.opts.secure ? "https" : "http";
  1009. var port = ""; // cache busting is forced
  1010. if (false !== this.opts.timestampRequests) {
  1011. query[this.opts.timestampParam] = yeast();
  1012. }
  1013. if (!this.supportsBinary && !query.sid) {
  1014. query.b64 = 1;
  1015. } // avoid port if default for schema
  1016. if (this.opts.port && ("https" === schema && Number(this.opts.port) !== 443 || "http" === schema && Number(this.opts.port) !== 80)) {
  1017. port = ":" + this.opts.port;
  1018. }
  1019. var encodedQuery = encode(query);
  1020. var ipv6 = this.opts.hostname.indexOf(":") !== -1;
  1021. return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : "");
  1022. }
  1023. /**
  1024. * Creates a request.
  1025. *
  1026. * @param {String} method
  1027. * @private
  1028. */
  1029. }, {
  1030. key: "request",
  1031. value: function request() {
  1032. var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1033. _extends(opts, {
  1034. xd: this.xd,
  1035. xs: this.xs
  1036. }, this.opts);
  1037. return new Request(this.uri(), opts);
  1038. }
  1039. /**
  1040. * Sends data.
  1041. *
  1042. * @param {String} data to send.
  1043. * @param {Function} called upon flush.
  1044. * @private
  1045. */
  1046. }, {
  1047. key: "doWrite",
  1048. value: function doWrite(data, fn) {
  1049. var _this6 = this;
  1050. var req = this.request({
  1051. method: "POST",
  1052. data: data
  1053. });
  1054. req.on("success", fn);
  1055. req.on("error", function (xhrStatus, context) {
  1056. _this6.onError("xhr post error", xhrStatus, context);
  1057. });
  1058. }
  1059. /**
  1060. * Starts a poll cycle.
  1061. *
  1062. * @private
  1063. */
  1064. }, {
  1065. key: "doPoll",
  1066. value: function doPoll() {
  1067. var _this7 = this;
  1068. var req = this.request();
  1069. req.on("data", this.onData.bind(this));
  1070. req.on("error", function (xhrStatus, context) {
  1071. _this7.onError("xhr poll error", xhrStatus, context);
  1072. });
  1073. this.pollXhr = req;
  1074. }
  1075. }]);
  1076. return Polling;
  1077. }(Transport);
  1078. var Request = /*#__PURE__*/function (_Emitter) {
  1079. _inherits(Request, _Emitter);
  1080. var _super2 = _createSuper(Request);
  1081. /**
  1082. * Request constructor
  1083. *
  1084. * @param {Object} options
  1085. * @package
  1086. */
  1087. function Request(uri, opts) {
  1088. var _this8;
  1089. _classCallCheck(this, Request);
  1090. _this8 = _super2.call(this);
  1091. installTimerFunctions(_assertThisInitialized(_this8), opts);
  1092. _this8.opts = opts;
  1093. _this8.method = opts.method || "GET";
  1094. _this8.uri = uri;
  1095. _this8.async = false !== opts.async;
  1096. _this8.data = undefined !== opts.data ? opts.data : null;
  1097. _this8.create();
  1098. return _this8;
  1099. }
  1100. /**
  1101. * Creates the XHR object and sends the request.
  1102. *
  1103. * @private
  1104. */
  1105. _createClass(Request, [{
  1106. key: "create",
  1107. value: function create() {
  1108. var _this9 = this;
  1109. var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
  1110. opts.xdomain = !!this.opts.xd;
  1111. opts.xscheme = !!this.opts.xs;
  1112. var xhr = this.xhr = new XHR(opts);
  1113. try {
  1114. xhr.open(this.method, this.uri, this.async);
  1115. try {
  1116. if (this.opts.extraHeaders) {
  1117. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  1118. for (var i in this.opts.extraHeaders) {
  1119. if (this.opts.extraHeaders.hasOwnProperty(i)) {
  1120. xhr.setRequestHeader(i, this.opts.extraHeaders[i]);
  1121. }
  1122. }
  1123. }
  1124. } catch (e) {}
  1125. if ("POST" === this.method) {
  1126. try {
  1127. xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
  1128. } catch (e) {}
  1129. }
  1130. try {
  1131. xhr.setRequestHeader("Accept", "*/*");
  1132. } catch (e) {} // ie6 check
  1133. if ("withCredentials" in xhr) {
  1134. xhr.withCredentials = this.opts.withCredentials;
  1135. }
  1136. if (this.opts.requestTimeout) {
  1137. xhr.timeout = this.opts.requestTimeout;
  1138. }
  1139. xhr.onreadystatechange = function () {
  1140. if (4 !== xhr.readyState) return;
  1141. if (200 === xhr.status || 1223 === xhr.status) {
  1142. _this9.onLoad();
  1143. } else {
  1144. // make sure the `error` event handler that's user-set
  1145. // does not throw in the same tick and gets caught here
  1146. _this9.setTimeoutFn(function () {
  1147. _this9.onError(typeof xhr.status === "number" ? xhr.status : 0);
  1148. }, 0);
  1149. }
  1150. };
  1151. xhr.send(this.data);
  1152. } catch (e) {
  1153. // Need to defer since .create() is called directly from the constructor
  1154. // and thus the 'error' event can only be only bound *after* this exception
  1155. // occurs. Therefore, also, we cannot throw here at all.
  1156. this.setTimeoutFn(function () {
  1157. _this9.onError(e);
  1158. }, 0);
  1159. return;
  1160. }
  1161. if (typeof document !== "undefined") {
  1162. this.index = Request.requestsCount++;
  1163. Request.requests[this.index] = this;
  1164. }
  1165. }
  1166. /**
  1167. * Called upon error.
  1168. *
  1169. * @private
  1170. */
  1171. }, {
  1172. key: "onError",
  1173. value: function onError(err) {
  1174. this.emitReserved("error", err, this.xhr);
  1175. this.cleanup(true);
  1176. }
  1177. /**
  1178. * Cleans up house.
  1179. *
  1180. * @private
  1181. */
  1182. }, {
  1183. key: "cleanup",
  1184. value: function cleanup(fromError) {
  1185. if ("undefined" === typeof this.xhr || null === this.xhr) {
  1186. return;
  1187. }
  1188. this.xhr.onreadystatechange = empty;
  1189. if (fromError) {
  1190. try {
  1191. this.xhr.abort();
  1192. } catch (e) {}
  1193. }
  1194. if (typeof document !== "undefined") {
  1195. delete Request.requests[this.index];
  1196. }
  1197. this.xhr = null;
  1198. }
  1199. /**
  1200. * Called upon load.
  1201. *
  1202. * @private
  1203. */
  1204. }, {
  1205. key: "onLoad",
  1206. value: function onLoad() {
  1207. var data = this.xhr.responseText;
  1208. if (data !== null) {
  1209. this.emitReserved("data", data);
  1210. this.emitReserved("success");
  1211. this.cleanup();
  1212. }
  1213. }
  1214. /**
  1215. * Aborts the request.
  1216. *
  1217. * @package
  1218. */
  1219. }, {
  1220. key: "abort",
  1221. value: function abort() {
  1222. this.cleanup();
  1223. }
  1224. }]);
  1225. return Request;
  1226. }(Emitter);
  1227. Request.requestsCount = 0;
  1228. Request.requests = {};
  1229. /**
  1230. * Aborts pending requests when unloading the window. This is needed to prevent
  1231. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  1232. * emitted.
  1233. */
  1234. if (typeof document !== "undefined") {
  1235. // @ts-ignore
  1236. if (typeof attachEvent === "function") {
  1237. // @ts-ignore
  1238. attachEvent("onunload", unloadHandler);
  1239. } else if (typeof addEventListener === "function") {
  1240. var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
  1241. addEventListener(terminationEvent, unloadHandler, false);
  1242. }
  1243. }
  1244. function unloadHandler() {
  1245. for (var i in Request.requests) {
  1246. if (Request.requests.hasOwnProperty(i)) {
  1247. Request.requests[i].abort();
  1248. }
  1249. }
  1250. }
  1251. var nextTick = function () {
  1252. var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
  1253. if (isPromiseAvailable) {
  1254. return function (cb) {
  1255. return Promise.resolve().then(cb);
  1256. };
  1257. } else {
  1258. return function (cb, setTimeoutFn) {
  1259. return setTimeoutFn(cb, 0);
  1260. };
  1261. }
  1262. }();
  1263. var WebSocket = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
  1264. var usingBrowserWebSocket = true;
  1265. var defaultBinaryType = "arraybuffer";
  1266. var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
  1267. var WS = /*#__PURE__*/function (_Transport) {
  1268. _inherits(WS, _Transport);
  1269. var _super = _createSuper(WS);
  1270. /**
  1271. * WebSocket transport constructor.
  1272. *
  1273. * @param {Object} opts - connection options
  1274. * @protected
  1275. */
  1276. function WS(opts) {
  1277. var _this;
  1278. _classCallCheck(this, WS);
  1279. _this = _super.call(this, opts);
  1280. _this.supportsBinary = !opts.forceBase64;
  1281. return _this;
  1282. }
  1283. _createClass(WS, [{
  1284. key: "name",
  1285. get: function get() {
  1286. return "websocket";
  1287. }
  1288. }, {
  1289. key: "doOpen",
  1290. value: function doOpen() {
  1291. if (!this.check()) {
  1292. // let probe timeout
  1293. return;
  1294. }
  1295. var uri = this.uri();
  1296. var protocols = this.opts.protocols; // React Native only supports the 'headers' option, and will print a warning if anything else is passed
  1297. var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
  1298. if (this.opts.extraHeaders) {
  1299. opts.headers = this.opts.extraHeaders;
  1300. }
  1301. try {
  1302. this.ws = usingBrowserWebSocket && !isReactNative ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts);
  1303. } catch (err) {
  1304. return this.emitReserved("error", err);
  1305. }
  1306. this.ws.binaryType = this.socket.binaryType || defaultBinaryType;
  1307. this.addEventListeners();
  1308. }
  1309. /**
  1310. * Adds event listeners to the socket
  1311. *
  1312. * @private
  1313. */
  1314. }, {
  1315. key: "addEventListeners",
  1316. value: function addEventListeners() {
  1317. var _this2 = this;
  1318. this.ws.onopen = function () {
  1319. if (_this2.opts.autoUnref) {
  1320. _this2.ws._socket.unref();
  1321. }
  1322. _this2.onOpen();
  1323. };
  1324. this.ws.onclose = function (closeEvent) {
  1325. return _this2.onClose({
  1326. description: "websocket connection closed",
  1327. context: closeEvent
  1328. });
  1329. };
  1330. this.ws.onmessage = function (ev) {
  1331. return _this2.onData(ev.data);
  1332. };
  1333. this.ws.onerror = function (e) {
  1334. return _this2.onError("websocket error", e);
  1335. };
  1336. }
  1337. }, {
  1338. key: "write",
  1339. value: function write(packets) {
  1340. var _this3 = this;
  1341. this.writable = false; // encodePacket efficient as it uses WS framing
  1342. // no need for encodePayload
  1343. var _loop = function _loop(i) {
  1344. var packet = packets[i];
  1345. var lastPacket = i === packets.length - 1;
  1346. encodePacket(packet, _this3.supportsBinary, function (data) {
  1347. // always create a new object (GH-437)
  1348. var opts = {};
  1349. // have a chance of informing us about it yet, in that case send will
  1350. // throw an error
  1351. try {
  1352. if (usingBrowserWebSocket) {
  1353. // TypeError is thrown when passing the second argument on Safari
  1354. _this3.ws.send(data);
  1355. }
  1356. } catch (e) {}
  1357. if (lastPacket) {
  1358. // fake drain
  1359. // defer to next tick to allow Socket to clear writeBuffer
  1360. nextTick(function () {
  1361. _this3.writable = true;
  1362. _this3.emitReserved("drain");
  1363. }, _this3.setTimeoutFn);
  1364. }
  1365. });
  1366. };
  1367. for (var i = 0; i < packets.length; i++) {
  1368. _loop(i);
  1369. }
  1370. }
  1371. }, {
  1372. key: "doClose",
  1373. value: function doClose() {
  1374. if (typeof this.ws !== "undefined") {
  1375. this.ws.close();
  1376. this.ws = null;
  1377. }
  1378. }
  1379. /**
  1380. * Generates uri for connection.
  1381. *
  1382. * @private
  1383. */
  1384. }, {
  1385. key: "uri",
  1386. value: function uri() {
  1387. var query = this.query || {};
  1388. var schema = this.opts.secure ? "wss" : "ws";
  1389. var port = ""; // avoid port if default for schema
  1390. if (this.opts.port && ("wss" === schema && Number(this.opts.port) !== 443 || "ws" === schema && Number(this.opts.port) !== 80)) {
  1391. port = ":" + this.opts.port;
  1392. } // append timestamp to URI
  1393. if (this.opts.timestampRequests) {
  1394. query[this.opts.timestampParam] = yeast();
  1395. } // communicate binary support capabilities
  1396. if (!this.supportsBinary) {
  1397. query.b64 = 1;
  1398. }
  1399. var encodedQuery = encode(query);
  1400. var ipv6 = this.opts.hostname.indexOf(":") !== -1;
  1401. return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : "");
  1402. }
  1403. /**
  1404. * Feature detection for WebSocket.
  1405. *
  1406. * @return {Boolean} whether this transport is available.
  1407. * @private
  1408. */
  1409. }, {
  1410. key: "check",
  1411. value: function check() {
  1412. return !!WebSocket;
  1413. }
  1414. }]);
  1415. return WS;
  1416. }(Transport);
  1417. var transports = {
  1418. websocket: WS,
  1419. polling: Polling
  1420. };
  1421. // imported from https://github.com/galkn/parseuri
  1422. /**
  1423. * Parses a URI
  1424. *
  1425. * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
  1426. *
  1427. * See:
  1428. * - https://developer.mozilla.org/en-US/docs/Web/API/URL
  1429. * - https://caniuse.com/url
  1430. * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
  1431. *
  1432. * History of the parse() method:
  1433. * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
  1434. * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
  1435. * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
  1436. *
  1437. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  1438. * @api private
  1439. */
  1440. var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  1441. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
  1442. function parse(str) {
  1443. var src = str,
  1444. b = str.indexOf('['),
  1445. e = str.indexOf(']');
  1446. if (b != -1 && e != -1) {
  1447. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  1448. }
  1449. var m = re.exec(str || ''),
  1450. uri = {},
  1451. i = 14;
  1452. while (i--) {
  1453. uri[parts[i]] = m[i] || '';
  1454. }
  1455. if (b != -1 && e != -1) {
  1456. uri.source = src;
  1457. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  1458. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  1459. uri.ipv6uri = true;
  1460. }
  1461. uri.pathNames = pathNames(uri, uri['path']);
  1462. uri.queryKey = queryKey(uri, uri['query']);
  1463. return uri;
  1464. }
  1465. function pathNames(obj, path) {
  1466. var regx = /\/{2,9}/g,
  1467. names = path.replace(regx, "/").split("/");
  1468. if (path.slice(0, 1) == '/' || path.length === 0) {
  1469. names.splice(0, 1);
  1470. }
  1471. if (path.slice(-1) == '/') {
  1472. names.splice(names.length - 1, 1);
  1473. }
  1474. return names;
  1475. }
  1476. function queryKey(uri, query) {
  1477. var data = {};
  1478. query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
  1479. if ($1) {
  1480. data[$1] = $2;
  1481. }
  1482. });
  1483. return data;
  1484. }
  1485. var Socket$1 = /*#__PURE__*/function (_Emitter) {
  1486. _inherits(Socket, _Emitter);
  1487. var _super = _createSuper(Socket);
  1488. /**
  1489. * Socket constructor.
  1490. *
  1491. * @param {String|Object} uri - uri or options
  1492. * @param {Object} opts - options
  1493. */
  1494. function Socket(uri) {
  1495. var _this;
  1496. var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1497. _classCallCheck(this, Socket);
  1498. _this = _super.call(this);
  1499. _this.writeBuffer = [];
  1500. if (uri && "object" === _typeof(uri)) {
  1501. opts = uri;
  1502. uri = null;
  1503. }
  1504. if (uri) {
  1505. uri = parse(uri);
  1506. opts.hostname = uri.host;
  1507. opts.secure = uri.protocol === "https" || uri.protocol === "wss";
  1508. opts.port = uri.port;
  1509. if (uri.query) opts.query = uri.query;
  1510. } else if (opts.host) {
  1511. opts.hostname = parse(opts.host).host;
  1512. }
  1513. installTimerFunctions(_assertThisInitialized(_this), opts);
  1514. _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
  1515. if (opts.hostname && !opts.port) {
  1516. // if no port is specified manually, use the protocol default
  1517. opts.port = _this.secure ? "443" : "80";
  1518. }
  1519. _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
  1520. _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
  1521. _this.transports = opts.transports || ["polling", "websocket"];
  1522. _this.writeBuffer = [];
  1523. _this.prevBufferLen = 0;
  1524. _this.opts = _extends({
  1525. path: "/engine.io",
  1526. agent: false,
  1527. withCredentials: false,
  1528. upgrade: true,
  1529. timestampParam: "t",
  1530. rememberUpgrade: false,
  1531. addTrailingSlash: true,
  1532. rejectUnauthorized: true,
  1533. perMessageDeflate: {
  1534. threshold: 1024
  1535. },
  1536. transportOptions: {},
  1537. closeOnBeforeunload: true
  1538. }, opts);
  1539. _this.opts.path = _this.opts.path.replace(/\/$/, "") + (_this.opts.addTrailingSlash ? "/" : "");
  1540. if (typeof _this.opts.query === "string") {
  1541. _this.opts.query = decode(_this.opts.query);
  1542. } // set on handshake
  1543. _this.id = null;
  1544. _this.upgrades = null;
  1545. _this.pingInterval = null;
  1546. _this.pingTimeout = null; // set on heartbeat
  1547. _this.pingTimeoutTimer = null;
  1548. if (typeof addEventListener === "function") {
  1549. if (_this.opts.closeOnBeforeunload) {
  1550. // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
  1551. // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
  1552. // closed/reloaded)
  1553. _this.beforeunloadEventListener = function () {
  1554. if (_this.transport) {
  1555. // silently close the transport
  1556. _this.transport.removeAllListeners();
  1557. _this.transport.close();
  1558. }
  1559. };
  1560. addEventListener("beforeunload", _this.beforeunloadEventListener, false);
  1561. }
  1562. if (_this.hostname !== "localhost") {
  1563. _this.offlineEventListener = function () {
  1564. _this.onClose("transport close", {
  1565. description: "network connection lost"
  1566. });
  1567. };
  1568. addEventListener("offline", _this.offlineEventListener, false);
  1569. }
  1570. }
  1571. _this.open();
  1572. return _this;
  1573. }
  1574. /**
  1575. * Creates transport of the given type.
  1576. *
  1577. * @param {String} name - transport name
  1578. * @return {Transport}
  1579. * @private
  1580. */
  1581. _createClass(Socket, [{
  1582. key: "createTransport",
  1583. value: function createTransport(name) {
  1584. var query = _extends({}, this.opts.query); // append engine.io protocol identifier
  1585. query.EIO = protocol$1; // transport name
  1586. query.transport = name; // session id if we already have one
  1587. if (this.id) query.sid = this.id;
  1588. var opts = _extends({}, this.opts.transportOptions[name], this.opts, {
  1589. query: query,
  1590. socket: this,
  1591. hostname: this.hostname,
  1592. secure: this.secure,
  1593. port: this.port
  1594. });
  1595. return new transports[name](opts);
  1596. }
  1597. /**
  1598. * Initializes transport to use and starts probe.
  1599. *
  1600. * @private
  1601. */
  1602. }, {
  1603. key: "open",
  1604. value: function open() {
  1605. var _this2 = this;
  1606. var transport;
  1607. if (this.opts.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1) {
  1608. transport = "websocket";
  1609. } else if (0 === this.transports.length) {
  1610. // Emit error on next tick so it can be listened to
  1611. this.setTimeoutFn(function () {
  1612. _this2.emitReserved("error", "No transports available");
  1613. }, 0);
  1614. return;
  1615. } else {
  1616. transport = this.transports[0];
  1617. }
  1618. this.readyState = "opening"; // Retry with the next transport if the transport is disabled (jsonp: false)
  1619. try {
  1620. transport = this.createTransport(transport);
  1621. } catch (e) {
  1622. this.transports.shift();
  1623. this.open();
  1624. return;
  1625. }
  1626. transport.open();
  1627. this.setTransport(transport);
  1628. }
  1629. /**
  1630. * Sets the current transport. Disables the existing one (if any).
  1631. *
  1632. * @private
  1633. */
  1634. }, {
  1635. key: "setTransport",
  1636. value: function setTransport(transport) {
  1637. var _this3 = this;
  1638. if (this.transport) {
  1639. this.transport.removeAllListeners();
  1640. } // set up transport
  1641. this.transport = transport; // set up transport listeners
  1642. transport.on("drain", this.onDrain.bind(this)).on("packet", this.onPacket.bind(this)).on("error", this.onError.bind(this)).on("close", function (reason) {
  1643. return _this3.onClose("transport close", reason);
  1644. });
  1645. }
  1646. /**
  1647. * Probes a transport.
  1648. *
  1649. * @param {String} name - transport name
  1650. * @private
  1651. */
  1652. }, {
  1653. key: "probe",
  1654. value: function probe(name) {
  1655. var _this4 = this;
  1656. var transport = this.createTransport(name);
  1657. var failed = false;
  1658. Socket.priorWebsocketSuccess = false;
  1659. var onTransportOpen = function onTransportOpen() {
  1660. if (failed) return;
  1661. transport.send([{
  1662. type: "ping",
  1663. data: "probe"
  1664. }]);
  1665. transport.once("packet", function (msg) {
  1666. if (failed) return;
  1667. if ("pong" === msg.type && "probe" === msg.data) {
  1668. _this4.upgrading = true;
  1669. _this4.emitReserved("upgrading", transport);
  1670. if (!transport) return;
  1671. Socket.priorWebsocketSuccess = "websocket" === transport.name;
  1672. _this4.transport.pause(function () {
  1673. if (failed) return;
  1674. if ("closed" === _this4.readyState) return;
  1675. cleanup();
  1676. _this4.setTransport(transport);
  1677. transport.send([{
  1678. type: "upgrade"
  1679. }]);
  1680. _this4.emitReserved("upgrade", transport);
  1681. transport = null;
  1682. _this4.upgrading = false;
  1683. _this4.flush();
  1684. });
  1685. } else {
  1686. var err = new Error("probe error"); // @ts-ignore
  1687. err.transport = transport.name;
  1688. _this4.emitReserved("upgradeError", err);
  1689. }
  1690. });
  1691. };
  1692. function freezeTransport() {
  1693. if (failed) return; // Any callback called by transport should be ignored since now
  1694. failed = true;
  1695. cleanup();
  1696. transport.close();
  1697. transport = null;
  1698. } // Handle any error that happens while probing
  1699. var onerror = function onerror(err) {
  1700. var error = new Error("probe error: " + err); // @ts-ignore
  1701. error.transport = transport.name;
  1702. freezeTransport();
  1703. _this4.emitReserved("upgradeError", error);
  1704. };
  1705. function onTransportClose() {
  1706. onerror("transport closed");
  1707. } // When the socket is closed while we're probing
  1708. function onclose() {
  1709. onerror("socket closed");
  1710. } // When the socket is upgraded while we're probing
  1711. function onupgrade(to) {
  1712. if (transport && to.name !== transport.name) {
  1713. freezeTransport();
  1714. }
  1715. } // Remove all listeners on the transport and on self
  1716. var cleanup = function cleanup() {
  1717. transport.removeListener("open", onTransportOpen);
  1718. transport.removeListener("error", onerror);
  1719. transport.removeListener("close", onTransportClose);
  1720. _this4.off("close", onclose);
  1721. _this4.off("upgrading", onupgrade);
  1722. };
  1723. transport.once("open", onTransportOpen);
  1724. transport.once("error", onerror);
  1725. transport.once("close", onTransportClose);
  1726. this.once("close", onclose);
  1727. this.once("upgrading", onupgrade);
  1728. transport.open();
  1729. }
  1730. /**
  1731. * Called when connection is deemed open.
  1732. *
  1733. * @private
  1734. */
  1735. }, {
  1736. key: "onOpen",
  1737. value: function onOpen() {
  1738. this.readyState = "open";
  1739. Socket.priorWebsocketSuccess = "websocket" === this.transport.name;
  1740. this.emitReserved("open");
  1741. this.flush(); // we check for `readyState` in case an `open`
  1742. // listener already closed the socket
  1743. if ("open" === this.readyState && this.opts.upgrade) {
  1744. var i = 0;
  1745. var l = this.upgrades.length;
  1746. for (; i < l; i++) {
  1747. this.probe(this.upgrades[i]);
  1748. }
  1749. }
  1750. }
  1751. /**
  1752. * Handles a packet.
  1753. *
  1754. * @private
  1755. */
  1756. }, {
  1757. key: "onPacket",
  1758. value: function onPacket(packet) {
  1759. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  1760. this.emitReserved("packet", packet); // Socket is live - any packet counts
  1761. this.emitReserved("heartbeat");
  1762. switch (packet.type) {
  1763. case "open":
  1764. this.onHandshake(JSON.parse(packet.data));
  1765. break;
  1766. case "ping":
  1767. this.resetPingTimeout();
  1768. this.sendPacket("pong");
  1769. this.emitReserved("ping");
  1770. this.emitReserved("pong");
  1771. break;
  1772. case "error":
  1773. var err = new Error("server error"); // @ts-ignore
  1774. err.code = packet.data;
  1775. this.onError(err);
  1776. break;
  1777. case "message":
  1778. this.emitReserved("data", packet.data);
  1779. this.emitReserved("message", packet.data);
  1780. break;
  1781. }
  1782. }
  1783. }
  1784. /**
  1785. * Called upon handshake completion.
  1786. *
  1787. * @param {Object} data - handshake obj
  1788. * @private
  1789. */
  1790. }, {
  1791. key: "onHandshake",
  1792. value: function onHandshake(data) {
  1793. this.emitReserved("handshake", data);
  1794. this.id = data.sid;
  1795. this.transport.query.sid = data.sid;
  1796. this.upgrades = this.filterUpgrades(data.upgrades);
  1797. this.pingInterval = data.pingInterval;
  1798. this.pingTimeout = data.pingTimeout;
  1799. this.maxPayload = data.maxPayload;
  1800. this.onOpen(); // In case open handler closes socket
  1801. if ("closed" === this.readyState) return;
  1802. this.resetPingTimeout();
  1803. }
  1804. /**
  1805. * Sets and resets ping timeout timer based on server pings.
  1806. *
  1807. * @private
  1808. */
  1809. }, {
  1810. key: "resetPingTimeout",
  1811. value: function resetPingTimeout() {
  1812. var _this5 = this;
  1813. this.clearTimeoutFn(this.pingTimeoutTimer);
  1814. this.pingTimeoutTimer = this.setTimeoutFn(function () {
  1815. _this5.onClose("ping timeout");
  1816. }, this.pingInterval + this.pingTimeout);
  1817. if (this.opts.autoUnref) {
  1818. this.pingTimeoutTimer.unref();
  1819. }
  1820. }
  1821. /**
  1822. * Called on `drain` event
  1823. *
  1824. * @private
  1825. */
  1826. }, {
  1827. key: "onDrain",
  1828. value: function onDrain() {
  1829. this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important
  1830. // for example, when upgrading, upgrade packet is sent over,
  1831. // and a nonzero prevBufferLen could cause problems on `drain`
  1832. this.prevBufferLen = 0;
  1833. if (0 === this.writeBuffer.length) {
  1834. this.emitReserved("drain");
  1835. } else {
  1836. this.flush();
  1837. }
  1838. }
  1839. /**
  1840. * Flush write buffers.
  1841. *
  1842. * @private
  1843. */
  1844. }, {
  1845. key: "flush",
  1846. value: function flush() {
  1847. if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
  1848. var packets = this.getWritablePackets();
  1849. this.transport.send(packets); // keep track of current length of writeBuffer
  1850. // splice writeBuffer and callbackBuffer on `drain`
  1851. this.prevBufferLen = packets.length;
  1852. this.emitReserved("flush");
  1853. }
  1854. }
  1855. /**
  1856. * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
  1857. * long-polling)
  1858. *
  1859. * @private
  1860. */
  1861. }, {
  1862. key: "getWritablePackets",
  1863. value: function getWritablePackets() {
  1864. var shouldCheckPayloadSize = this.maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
  1865. if (!shouldCheckPayloadSize) {
  1866. return this.writeBuffer;
  1867. }
  1868. var payloadSize = 1; // first packet type
  1869. for (var i = 0; i < this.writeBuffer.length; i++) {
  1870. var data = this.writeBuffer[i].data;
  1871. if (data) {
  1872. payloadSize += byteLength(data);
  1873. }
  1874. if (i > 0 && payloadSize > this.maxPayload) {
  1875. return this.writeBuffer.slice(0, i);
  1876. }
  1877. payloadSize += 2; // separator + packet type
  1878. }
  1879. return this.writeBuffer;
  1880. }
  1881. /**
  1882. * Sends a message.
  1883. *
  1884. * @param {String} msg - message.
  1885. * @param {Object} options.
  1886. * @param {Function} callback function.
  1887. * @return {Socket} for chaining.
  1888. */
  1889. }, {
  1890. key: "write",
  1891. value: function write(msg, options, fn) {
  1892. this.sendPacket("message", msg, options, fn);
  1893. return this;
  1894. }
  1895. }, {
  1896. key: "send",
  1897. value: function send(msg, options, fn) {
  1898. this.sendPacket("message", msg, options, fn);
  1899. return this;
  1900. }
  1901. /**
  1902. * Sends a packet.
  1903. *
  1904. * @param {String} type: packet type.
  1905. * @param {String} data.
  1906. * @param {Object} options.
  1907. * @param {Function} fn - callback function.
  1908. * @private
  1909. */
  1910. }, {
  1911. key: "sendPacket",
  1912. value: function sendPacket(type, data, options, fn) {
  1913. if ("function" === typeof data) {
  1914. fn = data;
  1915. data = undefined;
  1916. }
  1917. if ("function" === typeof options) {
  1918. fn = options;
  1919. options = null;
  1920. }
  1921. if ("closing" === this.readyState || "closed" === this.readyState) {
  1922. return;
  1923. }
  1924. options = options || {};
  1925. options.compress = false !== options.compress;
  1926. var packet = {
  1927. type: type,
  1928. data: data,
  1929. options: options
  1930. };
  1931. this.emitReserved("packetCreate", packet);
  1932. this.writeBuffer.push(packet);
  1933. if (fn) this.once("flush", fn);
  1934. this.flush();
  1935. }
  1936. /**
  1937. * Closes the connection.
  1938. */
  1939. }, {
  1940. key: "close",
  1941. value: function close() {
  1942. var _this6 = this;
  1943. var close = function close() {
  1944. _this6.onClose("forced close");
  1945. _this6.transport.close();
  1946. };
  1947. var cleanupAndClose = function cleanupAndClose() {
  1948. _this6.off("upgrade", cleanupAndClose);
  1949. _this6.off("upgradeError", cleanupAndClose);
  1950. close();
  1951. };
  1952. var waitForUpgrade = function waitForUpgrade() {
  1953. // wait for upgrade to finish since we can't send packets while pausing a transport
  1954. _this6.once("upgrade", cleanupAndClose);
  1955. _this6.once("upgradeError", cleanupAndClose);
  1956. };
  1957. if ("opening" === this.readyState || "open" === this.readyState) {
  1958. this.readyState = "closing";
  1959. if (this.writeBuffer.length) {
  1960. this.once("drain", function () {
  1961. if (_this6.upgrading) {
  1962. waitForUpgrade();
  1963. } else {
  1964. close();
  1965. }
  1966. });
  1967. } else if (this.upgrading) {
  1968. waitForUpgrade();
  1969. } else {
  1970. close();
  1971. }
  1972. }
  1973. return this;
  1974. }
  1975. /**
  1976. * Called upon transport error
  1977. *
  1978. * @private
  1979. */
  1980. }, {
  1981. key: "onError",
  1982. value: function onError(err) {
  1983. Socket.priorWebsocketSuccess = false;
  1984. this.emitReserved("error", err);
  1985. this.onClose("transport error", err);
  1986. }
  1987. /**
  1988. * Called upon transport close.
  1989. *
  1990. * @private
  1991. */
  1992. }, {
  1993. key: "onClose",
  1994. value: function onClose(reason, description) {
  1995. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  1996. // clear timers
  1997. this.clearTimeoutFn(this.pingTimeoutTimer); // stop event from firing again for transport
  1998. this.transport.removeAllListeners("close"); // ensure transport won't stay open
  1999. this.transport.close(); // ignore further transport communication
  2000. this.transport.removeAllListeners();
  2001. if (typeof removeEventListener === "function") {
  2002. removeEventListener("beforeunload", this.beforeunloadEventListener, false);
  2003. removeEventListener("offline", this.offlineEventListener, false);
  2004. } // set ready state
  2005. this.readyState = "closed"; // clear session id
  2006. this.id = null; // emit close event
  2007. this.emitReserved("close", reason, description); // clean buffers after, so users can still
  2008. // grab the buffers on `close` event
  2009. this.writeBuffer = [];
  2010. this.prevBufferLen = 0;
  2011. }
  2012. }
  2013. /**
  2014. * Filters upgrades, returning only those matching client transports.
  2015. *
  2016. * @param {Array} upgrades - server upgrades
  2017. * @private
  2018. */
  2019. }, {
  2020. key: "filterUpgrades",
  2021. value: function filterUpgrades(upgrades) {
  2022. var filteredUpgrades = [];
  2023. var i = 0;
  2024. var j = upgrades.length;
  2025. for (; i < j; i++) {
  2026. if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
  2027. }
  2028. return filteredUpgrades;
  2029. }
  2030. }]);
  2031. return Socket;
  2032. }(Emitter);
  2033. Socket$1.protocol = protocol$1;
  2034. Socket$1.protocol;
  2035. /**
  2036. * URL parser.
  2037. *
  2038. * @param uri - url
  2039. * @param path - the request path of the connection
  2040. * @param loc - An object meant to mimic window.location.
  2041. * Defaults to window.location.
  2042. * @public
  2043. */
  2044. function url(uri) {
  2045. var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  2046. var loc = arguments.length > 2 ? arguments[2] : undefined;
  2047. var obj = uri; // default to window.location
  2048. loc = loc || typeof location !== "undefined" && location;
  2049. if (null == uri) uri = loc.protocol + "//" + loc.host; // relative path support
  2050. if (typeof uri === "string") {
  2051. if ("/" === uri.charAt(0)) {
  2052. if ("/" === uri.charAt(1)) {
  2053. uri = loc.protocol + uri;
  2054. } else {
  2055. uri = loc.host + uri;
  2056. }
  2057. }
  2058. if (!/^(https?|wss?):\/\//.test(uri)) {
  2059. if ("undefined" !== typeof loc) {
  2060. uri = loc.protocol + "//" + uri;
  2061. } else {
  2062. uri = "https://" + uri;
  2063. }
  2064. } // parse
  2065. obj = parse(uri);
  2066. } // make sure we treat `localhost:80` and `localhost` equally
  2067. if (!obj.port) {
  2068. if (/^(http|ws)$/.test(obj.protocol)) {
  2069. obj.port = "80";
  2070. } else if (/^(http|ws)s$/.test(obj.protocol)) {
  2071. obj.port = "443";
  2072. }
  2073. }
  2074. obj.path = obj.path || "/";
  2075. var ipv6 = obj.host.indexOf(":") !== -1;
  2076. var host = ipv6 ? "[" + obj.host + "]" : obj.host; // define unique id
  2077. obj.id = obj.protocol + "://" + host + ":" + obj.port + path; // define href
  2078. obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
  2079. return obj;
  2080. }
  2081. var withNativeArrayBuffer = typeof ArrayBuffer === "function";
  2082. var isView = function isView(obj) {
  2083. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
  2084. };
  2085. var toString = Object.prototype.toString;
  2086. var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
  2087. var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
  2088. /**
  2089. * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
  2090. *
  2091. * @private
  2092. */
  2093. function isBinary(obj) {
  2094. return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File;
  2095. }
  2096. function hasBinary(obj, toJSON) {
  2097. if (!obj || _typeof(obj) !== "object") {
  2098. return false;
  2099. }
  2100. if (Array.isArray(obj)) {
  2101. for (var i = 0, l = obj.length; i < l; i++) {
  2102. if (hasBinary(obj[i])) {
  2103. return true;
  2104. }
  2105. }
  2106. return false;
  2107. }
  2108. if (isBinary(obj)) {
  2109. return true;
  2110. }
  2111. if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
  2112. return hasBinary(obj.toJSON(), true);
  2113. }
  2114. for (var key in obj) {
  2115. if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
  2116. return true;
  2117. }
  2118. }
  2119. return false;
  2120. }
  2121. /**
  2122. * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
  2123. *
  2124. * @param {Object} packet - socket.io event packet
  2125. * @return {Object} with deconstructed packet and list of buffers
  2126. * @public
  2127. */
  2128. function deconstructPacket(packet) {
  2129. var buffers = [];
  2130. var packetData = packet.data;
  2131. var pack = packet;
  2132. pack.data = _deconstructPacket(packetData, buffers);
  2133. pack.attachments = buffers.length; // number of binary 'attachments'
  2134. return {
  2135. packet: pack,
  2136. buffers: buffers
  2137. };
  2138. }
  2139. function _deconstructPacket(data, buffers) {
  2140. if (!data) return data;
  2141. if (isBinary(data)) {
  2142. var placeholder = {
  2143. _placeholder: true,
  2144. num: buffers.length
  2145. };
  2146. buffers.push(data);
  2147. return placeholder;
  2148. } else if (Array.isArray(data)) {
  2149. var newData = new Array(data.length);
  2150. for (var i = 0; i < data.length; i++) {
  2151. newData[i] = _deconstructPacket(data[i], buffers);
  2152. }
  2153. return newData;
  2154. } else if (_typeof(data) === "object" && !(data instanceof Date)) {
  2155. var _newData = {};
  2156. for (var key in data) {
  2157. if (Object.prototype.hasOwnProperty.call(data, key)) {
  2158. _newData[key] = _deconstructPacket(data[key], buffers);
  2159. }
  2160. }
  2161. return _newData;
  2162. }
  2163. return data;
  2164. }
  2165. /**
  2166. * Reconstructs a binary packet from its placeholder packet and buffers
  2167. *
  2168. * @param {Object} packet - event packet with placeholders
  2169. * @param {Array} buffers - binary buffers to put in placeholder positions
  2170. * @return {Object} reconstructed packet
  2171. * @public
  2172. */
  2173. function reconstructPacket(packet, buffers) {
  2174. packet.data = _reconstructPacket(packet.data, buffers);
  2175. delete packet.attachments; // no longer useful
  2176. return packet;
  2177. }
  2178. function _reconstructPacket(data, buffers) {
  2179. if (!data) return data;
  2180. if (data && data._placeholder === true) {
  2181. var isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
  2182. if (isIndexValid) {
  2183. return buffers[data.num]; // appropriate buffer (should be natural order anyway)
  2184. } else {
  2185. throw new Error("illegal attachments");
  2186. }
  2187. } else if (Array.isArray(data)) {
  2188. for (var i = 0; i < data.length; i++) {
  2189. data[i] = _reconstructPacket(data[i], buffers);
  2190. }
  2191. } else if (_typeof(data) === "object") {
  2192. for (var key in data) {
  2193. if (Object.prototype.hasOwnProperty.call(data, key)) {
  2194. data[key] = _reconstructPacket(data[key], buffers);
  2195. }
  2196. }
  2197. }
  2198. return data;
  2199. }
  2200. /**
  2201. * These strings must not be used as event names, as they have a special meaning.
  2202. */
  2203. var RESERVED_EVENTS$1 = ["connect", "connect_error", "disconnect", "disconnecting", "newListener", "removeListener" // used by the Node.js EventEmitter
  2204. ];
  2205. /**
  2206. * Protocol version.
  2207. *
  2208. * @public
  2209. */
  2210. var protocol = 5;
  2211. var PacketType;
  2212. (function (PacketType) {
  2213. PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
  2214. PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
  2215. PacketType[PacketType["EVENT"] = 2] = "EVENT";
  2216. PacketType[PacketType["ACK"] = 3] = "ACK";
  2217. PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
  2218. PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
  2219. PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
  2220. })(PacketType || (PacketType = {}));
  2221. /**
  2222. * A socket.io Encoder instance
  2223. */
  2224. var Encoder = /*#__PURE__*/function () {
  2225. /**
  2226. * Encoder constructor
  2227. *
  2228. * @param {function} replacer - custom replacer to pass down to JSON.parse
  2229. */
  2230. function Encoder(replacer) {
  2231. _classCallCheck(this, Encoder);
  2232. this.replacer = replacer;
  2233. }
  2234. /**
  2235. * Encode a packet as a single string if non-binary, or as a
  2236. * buffer sequence, depending on packet type.
  2237. *
  2238. * @param {Object} obj - packet object
  2239. */
  2240. _createClass(Encoder, [{
  2241. key: "encode",
  2242. value: function encode(obj) {
  2243. if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
  2244. if (hasBinary(obj)) {
  2245. return this.encodeAsBinary({
  2246. type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
  2247. nsp: obj.nsp,
  2248. data: obj.data,
  2249. id: obj.id
  2250. });
  2251. }
  2252. }
  2253. return [this.encodeAsString(obj)];
  2254. }
  2255. /**
  2256. * Encode packet as string.
  2257. */
  2258. }, {
  2259. key: "encodeAsString",
  2260. value: function encodeAsString(obj) {
  2261. // first is type
  2262. var str = "" + obj.type; // attachments if we have them
  2263. if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
  2264. str += obj.attachments + "-";
  2265. } // if we have a namespace other than `/`
  2266. // we append it followed by a comma `,`
  2267. if (obj.nsp && "/" !== obj.nsp) {
  2268. str += obj.nsp + ",";
  2269. } // immediately followed by the id
  2270. if (null != obj.id) {
  2271. str += obj.id;
  2272. } // json data
  2273. if (null != obj.data) {
  2274. str += JSON.stringify(obj.data, this.replacer);
  2275. }
  2276. return str;
  2277. }
  2278. /**
  2279. * Encode packet as 'buffer sequence' by removing blobs, and
  2280. * deconstructing packet into object with placeholders and
  2281. * a list of buffers.
  2282. */
  2283. }, {
  2284. key: "encodeAsBinary",
  2285. value: function encodeAsBinary(obj) {
  2286. var deconstruction = deconstructPacket(obj);
  2287. var pack = this.encodeAsString(deconstruction.packet);
  2288. var buffers = deconstruction.buffers;
  2289. buffers.unshift(pack); // add packet info to beginning of data list
  2290. return buffers; // write all the buffers
  2291. }
  2292. }]);
  2293. return Encoder;
  2294. }(); // see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
  2295. function isObject(value) {
  2296. return Object.prototype.toString.call(value) === "[object Object]";
  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. if (this.reconstructor) {
  2329. throw new Error("got plaintext data when reconstructing a packet");
  2330. }
  2331. packet = this.decodeString(obj);
  2332. var isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
  2333. if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
  2334. packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK; // binary packet's json
  2335. this.reconstructor = new BinaryReconstructor(packet); // no attachments, labeled binary but no binary data to follow
  2336. if (packet.attachments === 0) {
  2337. _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
  2338. }
  2339. } else {
  2340. // non-binary full packet
  2341. _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
  2342. }
  2343. } else if (isBinary(obj) || obj.base64) {
  2344. // raw binary data
  2345. if (!this.reconstructor) {
  2346. throw new Error("got binary data when not reconstructing a packet");
  2347. } else {
  2348. packet = this.reconstructor.takeBinaryData(obj);
  2349. if (packet) {
  2350. // received final buffer
  2351. this.reconstructor = null;
  2352. _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
  2353. }
  2354. }
  2355. } else {
  2356. throw new Error("Unknown type: " + obj);
  2357. }
  2358. }
  2359. /**
  2360. * Decode a packet String (JSON data)
  2361. *
  2362. * @param {String} str
  2363. * @return {Object} packet
  2364. */
  2365. }, {
  2366. key: "decodeString",
  2367. value: function decodeString(str) {
  2368. var i = 0; // look up type
  2369. var p = {
  2370. type: Number(str.charAt(0))
  2371. };
  2372. if (PacketType[p.type] === undefined) {
  2373. throw new Error("unknown packet type " + p.type);
  2374. } // look up attachments if type binary
  2375. if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
  2376. var start = i + 1;
  2377. while (str.charAt(++i) !== "-" && i != str.length) {}
  2378. var buf = str.substring(start, i);
  2379. if (buf != Number(buf) || str.charAt(i) !== "-") {
  2380. throw new Error("Illegal attachments");
  2381. }
  2382. p.attachments = Number(buf);
  2383. } // look up namespace (if any)
  2384. if ("/" === str.charAt(i + 1)) {
  2385. var _start = i + 1;
  2386. while (++i) {
  2387. var c = str.charAt(i);
  2388. if ("," === c) break;
  2389. if (i === str.length) break;
  2390. }
  2391. p.nsp = str.substring(_start, i);
  2392. } else {
  2393. p.nsp = "/";
  2394. } // look up id
  2395. var next = str.charAt(i + 1);
  2396. if ("" !== next && Number(next) == next) {
  2397. var _start2 = i + 1;
  2398. while (++i) {
  2399. var _c = str.charAt(i);
  2400. if (null == _c || Number(_c) != _c) {
  2401. --i;
  2402. break;
  2403. }
  2404. if (i === str.length) break;
  2405. }
  2406. p.id = Number(str.substring(_start2, i + 1));
  2407. } // look up json data
  2408. if (str.charAt(++i)) {
  2409. var payload = this.tryParse(str.substr(i));
  2410. if (Decoder.isPayloadValid(p.type, payload)) {
  2411. p.data = payload;
  2412. } else {
  2413. throw new Error("invalid payload");
  2414. }
  2415. }
  2416. return p;
  2417. }
  2418. }, {
  2419. key: "tryParse",
  2420. value: function tryParse(str) {
  2421. try {
  2422. return JSON.parse(str, this.reviver);
  2423. } catch (e) {
  2424. return false;
  2425. }
  2426. }
  2427. }, {
  2428. key: "destroy",
  2429. value:
  2430. /**
  2431. * Deallocates a parser's resources
  2432. */
  2433. function destroy() {
  2434. if (this.reconstructor) {
  2435. this.reconstructor.finishedReconstruction();
  2436. this.reconstructor = null;
  2437. }
  2438. }
  2439. }], [{
  2440. key: "isPayloadValid",
  2441. value: function isPayloadValid(type, payload) {
  2442. switch (type) {
  2443. case PacketType.CONNECT:
  2444. return isObject(payload);
  2445. case PacketType.DISCONNECT:
  2446. return payload === undefined;
  2447. case PacketType.CONNECT_ERROR:
  2448. return typeof payload === "string" || isObject(payload);
  2449. case PacketType.EVENT:
  2450. case PacketType.BINARY_EVENT:
  2451. return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
  2452. case PacketType.ACK:
  2453. case PacketType.BINARY_ACK:
  2454. return Array.isArray(payload);
  2455. }
  2456. }
  2457. }]);
  2458. return Decoder;
  2459. }(Emitter);
  2460. /**
  2461. * A manager of a binary event's 'buffer sequence'. Should
  2462. * be constructed whenever a packet of type BINARY_EVENT is
  2463. * decoded.
  2464. *
  2465. * @param {Object} packet
  2466. * @return {BinaryReconstructor} initialized reconstructor
  2467. */
  2468. var BinaryReconstructor = /*#__PURE__*/function () {
  2469. function BinaryReconstructor(packet) {
  2470. _classCallCheck(this, BinaryReconstructor);
  2471. this.packet = packet;
  2472. this.buffers = [];
  2473. this.reconPack = packet;
  2474. }
  2475. /**
  2476. * Method to be called when binary data received from connection
  2477. * after a BINARY_EVENT packet.
  2478. *
  2479. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  2480. * @return {null | Object} returns null if more binary data is expected or
  2481. * a reconstructed packet object if all buffers have been received.
  2482. */
  2483. _createClass(BinaryReconstructor, [{
  2484. key: "takeBinaryData",
  2485. value: function takeBinaryData(binData) {
  2486. this.buffers.push(binData);
  2487. if (this.buffers.length === this.reconPack.attachments) {
  2488. // done with buffer list
  2489. var packet = reconstructPacket(this.reconPack, this.buffers);
  2490. this.finishedReconstruction();
  2491. return packet;
  2492. }
  2493. return null;
  2494. }
  2495. /**
  2496. * Cleans up binary packet reconstruction variables.
  2497. */
  2498. }, {
  2499. key: "finishedReconstruction",
  2500. value: function finishedReconstruction() {
  2501. this.reconPack = null;
  2502. this.buffers = [];
  2503. }
  2504. }]);
  2505. return BinaryReconstructor;
  2506. }();
  2507. var parser = /*#__PURE__*/Object.freeze({
  2508. __proto__: null,
  2509. protocol: protocol,
  2510. get PacketType () { return PacketType; },
  2511. Encoder: Encoder,
  2512. Decoder: Decoder
  2513. });
  2514. function on(obj, ev, fn) {
  2515. obj.on(ev, fn);
  2516. return function subDestroy() {
  2517. obj.off(ev, fn);
  2518. };
  2519. }
  2520. /**
  2521. * Internal events.
  2522. * These events can't be emitted by the user.
  2523. */
  2524. var RESERVED_EVENTS = Object.freeze({
  2525. connect: 1,
  2526. connect_error: 1,
  2527. disconnect: 1,
  2528. disconnecting: 1,
  2529. // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
  2530. newListener: 1,
  2531. removeListener: 1
  2532. });
  2533. /**
  2534. * A Socket is the fundamental class for interacting with the server.
  2535. *
  2536. * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
  2537. *
  2538. * @example
  2539. * const socket = io();
  2540. *
  2541. * socket.on("connect", () => {
  2542. * console.log("connected");
  2543. * });
  2544. *
  2545. * // send an event to the server
  2546. * socket.emit("foo", "bar");
  2547. *
  2548. * socket.on("foobar", () => {
  2549. * // an event was received from the server
  2550. * });
  2551. *
  2552. * // upon disconnection
  2553. * socket.on("disconnect", (reason) => {
  2554. * console.log(`disconnected due to ${reason}`);
  2555. * });
  2556. */
  2557. var Socket = /*#__PURE__*/function (_Emitter) {
  2558. _inherits(Socket, _Emitter);
  2559. var _super = _createSuper(Socket);
  2560. /**
  2561. * `Socket` constructor.
  2562. */
  2563. function Socket(io, nsp, opts) {
  2564. var _this;
  2565. _classCallCheck(this, Socket);
  2566. _this = _super.call(this);
  2567. /**
  2568. * Whether the socket is currently connected to the server.
  2569. *
  2570. * @example
  2571. * const socket = io();
  2572. *
  2573. * socket.on("connect", () => {
  2574. * console.log(socket.connected); // true
  2575. * });
  2576. *
  2577. * socket.on("disconnect", () => {
  2578. * console.log(socket.connected); // false
  2579. * });
  2580. */
  2581. _this.connected = false;
  2582. /**
  2583. * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
  2584. * be transmitted by the server.
  2585. */
  2586. _this.recovered = false;
  2587. /**
  2588. * Buffer for packets received before the CONNECT packet
  2589. */
  2590. _this.receiveBuffer = [];
  2591. /**
  2592. * Buffer for packets that will be sent once the socket is connected
  2593. */
  2594. _this.sendBuffer = [];
  2595. /**
  2596. * The queue of packets to be sent with retry in case of failure.
  2597. *
  2598. * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
  2599. * @private
  2600. */
  2601. _this._queue = [];
  2602. /**
  2603. * A sequence to generate the ID of the {@link QueuedPacket}.
  2604. * @private
  2605. */
  2606. _this._queueSeq = 0;
  2607. _this.ids = 0;
  2608. _this.acks = {};
  2609. _this.flags = {};
  2610. _this.io = io;
  2611. _this.nsp = nsp;
  2612. if (opts && opts.auth) {
  2613. _this.auth = opts.auth;
  2614. }
  2615. _this._opts = _extends({}, opts);
  2616. if (_this.io._autoConnect) _this.open();
  2617. return _this;
  2618. }
  2619. /**
  2620. * Whether the socket is currently disconnected
  2621. *
  2622. * @example
  2623. * const socket = io();
  2624. *
  2625. * socket.on("connect", () => {
  2626. * console.log(socket.disconnected); // false
  2627. * });
  2628. *
  2629. * socket.on("disconnect", () => {
  2630. * console.log(socket.disconnected); // true
  2631. * });
  2632. */
  2633. _createClass(Socket, [{
  2634. key: "disconnected",
  2635. get: function get() {
  2636. return !this.connected;
  2637. }
  2638. /**
  2639. * Subscribe to open, close and packet events
  2640. *
  2641. * @private
  2642. */
  2643. }, {
  2644. key: "subEvents",
  2645. value: function subEvents() {
  2646. if (this.subs) return;
  2647. var io = this.io;
  2648. 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))];
  2649. }
  2650. /**
  2651. * Whether the Socket will try to reconnect when its Manager connects or reconnects.
  2652. *
  2653. * @example
  2654. * const socket = io();
  2655. *
  2656. * console.log(socket.active); // true
  2657. *
  2658. * socket.on("disconnect", (reason) => {
  2659. * if (reason === "io server disconnect") {
  2660. * // the disconnection was initiated by the server, you need to manually reconnect
  2661. * console.log(socket.active); // false
  2662. * }
  2663. * // else the socket will automatically try to reconnect
  2664. * console.log(socket.active); // true
  2665. * });
  2666. */
  2667. }, {
  2668. key: "active",
  2669. get: function get() {
  2670. return !!this.subs;
  2671. }
  2672. /**
  2673. * "Opens" the socket.
  2674. *
  2675. * @example
  2676. * const socket = io({
  2677. * autoConnect: false
  2678. * });
  2679. *
  2680. * socket.connect();
  2681. */
  2682. }, {
  2683. key: "connect",
  2684. value: function connect() {
  2685. if (this.connected) return this;
  2686. this.subEvents();
  2687. if (!this.io["_reconnecting"]) this.io.open(); // ensure open
  2688. if ("open" === this.io._readyState) this.onopen();
  2689. return this;
  2690. }
  2691. /**
  2692. * Alias for {@link connect()}.
  2693. */
  2694. }, {
  2695. key: "open",
  2696. value: function open() {
  2697. return this.connect();
  2698. }
  2699. /**
  2700. * Sends a `message` event.
  2701. *
  2702. * This method mimics the WebSocket.send() method.
  2703. *
  2704. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  2705. *
  2706. * @example
  2707. * socket.send("hello");
  2708. *
  2709. * // this is equivalent to
  2710. * socket.emit("message", "hello");
  2711. *
  2712. * @return self
  2713. */
  2714. }, {
  2715. key: "send",
  2716. value: function send() {
  2717. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2718. args[_key] = arguments[_key];
  2719. }
  2720. args.unshift("message");
  2721. this.emit.apply(this, args);
  2722. return this;
  2723. }
  2724. /**
  2725. * Override `emit`.
  2726. * If the event is in `events`, it's emitted normally.
  2727. *
  2728. * @example
  2729. * socket.emit("hello", "world");
  2730. *
  2731. * // all serializable datastructures are supported (no need to call JSON.stringify)
  2732. * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
  2733. *
  2734. * // with an acknowledgement from the server
  2735. * socket.emit("hello", "world", (val) => {
  2736. * // ...
  2737. * });
  2738. *
  2739. * @return self
  2740. */
  2741. }, {
  2742. key: "emit",
  2743. value: function emit(ev) {
  2744. if (RESERVED_EVENTS.hasOwnProperty(ev)) {
  2745. throw new Error('"' + ev.toString() + '" is a reserved event name');
  2746. }
  2747. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  2748. args[_key2 - 1] = arguments[_key2];
  2749. }
  2750. args.unshift(ev);
  2751. if (this._opts.retries && !this.flags.fromQueue && !this.flags["volatile"]) {
  2752. this._addToQueue(args);
  2753. return this;
  2754. }
  2755. var packet = {
  2756. type: PacketType.EVENT,
  2757. data: args
  2758. };
  2759. packet.options = {};
  2760. packet.options.compress = this.flags.compress !== false; // event ack callback
  2761. if ("function" === typeof args[args.length - 1]) {
  2762. var id = this.ids++;
  2763. var ack = args.pop();
  2764. this._registerAckCallback(id, ack);
  2765. packet.id = id;
  2766. }
  2767. var isTransportWritable = this.io.engine && this.io.engine.transport && this.io.engine.transport.writable;
  2768. var discardPacket = this.flags["volatile"] && (!isTransportWritable || !this.connected);
  2769. if (discardPacket) ; else if (this.connected) {
  2770. this.notifyOutgoingListeners(packet);
  2771. this.packet(packet);
  2772. } else {
  2773. this.sendBuffer.push(packet);
  2774. }
  2775. this.flags = {};
  2776. return this;
  2777. }
  2778. /**
  2779. * @private
  2780. */
  2781. }, {
  2782. key: "_registerAckCallback",
  2783. value: function _registerAckCallback(id, ack) {
  2784. var _this2 = this;
  2785. var _a;
  2786. var timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
  2787. if (timeout === undefined) {
  2788. this.acks[id] = ack;
  2789. return;
  2790. } // @ts-ignore
  2791. var timer = this.io.setTimeoutFn(function () {
  2792. delete _this2.acks[id];
  2793. for (var i = 0; i < _this2.sendBuffer.length; i++) {
  2794. if (_this2.sendBuffer[i].id === id) {
  2795. _this2.sendBuffer.splice(i, 1);
  2796. }
  2797. }
  2798. ack.call(_this2, new Error("operation has timed out"));
  2799. }, timeout);
  2800. this.acks[id] = function () {
  2801. // @ts-ignore
  2802. _this2.io.clearTimeoutFn(timer);
  2803. for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  2804. args[_key3] = arguments[_key3];
  2805. }
  2806. ack.apply(_this2, [null].concat(args));
  2807. };
  2808. }
  2809. /**
  2810. * Emits an event and waits for an acknowledgement
  2811. *
  2812. * @example
  2813. * // without timeout
  2814. * const response = await socket.emitWithAck("hello", "world");
  2815. *
  2816. * // with a specific timeout
  2817. * try {
  2818. * const response = await socket.timeout(1000).emitWithAck("hello", "world");
  2819. * } catch (err) {
  2820. * // the server did not acknowledge the event in the given delay
  2821. * }
  2822. *
  2823. * @return a Promise that will be fulfilled when the server acknowledges the event
  2824. */
  2825. }, {
  2826. key: "emitWithAck",
  2827. value: function emitWithAck(ev) {
  2828. var _this3 = this;
  2829. for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
  2830. args[_key4 - 1] = arguments[_key4];
  2831. }
  2832. // the timeout flag is optional
  2833. var withErr = this.flags.timeout !== undefined || this._opts.ackTimeout !== undefined;
  2834. return new Promise(function (resolve, reject) {
  2835. args.push(function (arg1, arg2) {
  2836. if (withErr) {
  2837. return arg1 ? reject(arg1) : resolve(arg2);
  2838. } else {
  2839. return resolve(arg1);
  2840. }
  2841. });
  2842. _this3.emit.apply(_this3, [ev].concat(args));
  2843. });
  2844. }
  2845. /**
  2846. * Add the packet to the queue.
  2847. * @param args
  2848. * @private
  2849. */
  2850. }, {
  2851. key: "_addToQueue",
  2852. value: function _addToQueue(args) {
  2853. var _this4 = this;
  2854. var ack;
  2855. if (typeof args[args.length - 1] === "function") {
  2856. ack = args.pop();
  2857. }
  2858. var packet = {
  2859. id: this._queueSeq++,
  2860. tryCount: 0,
  2861. pending: false,
  2862. args: args,
  2863. flags: _extends({
  2864. fromQueue: true
  2865. }, this.flags)
  2866. };
  2867. args.push(function (err) {
  2868. if (packet !== _this4._queue[0]) {
  2869. // the packet has already been acknowledged
  2870. return;
  2871. }
  2872. var hasError = err !== null;
  2873. if (hasError) {
  2874. if (packet.tryCount > _this4._opts.retries) {
  2875. _this4._queue.shift();
  2876. if (ack) {
  2877. ack(err);
  2878. }
  2879. }
  2880. } else {
  2881. _this4._queue.shift();
  2882. if (ack) {
  2883. for (var _len5 = arguments.length, responseArgs = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
  2884. responseArgs[_key5 - 1] = arguments[_key5];
  2885. }
  2886. ack.apply(void 0, [null].concat(responseArgs));
  2887. }
  2888. }
  2889. packet.pending = false;
  2890. return _this4._drainQueue();
  2891. });
  2892. this._queue.push(packet);
  2893. this._drainQueue();
  2894. }
  2895. /**
  2896. * Send the first packet of the queue, and wait for an acknowledgement from the server.
  2897. * @param force - whether to resend a packet that has not been acknowledged yet
  2898. *
  2899. * @private
  2900. */
  2901. }, {
  2902. key: "_drainQueue",
  2903. value: function _drainQueue() {
  2904. var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  2905. if (!this.connected || this._queue.length === 0) {
  2906. return;
  2907. }
  2908. var packet = this._queue[0];
  2909. if (packet.pending && !force) {
  2910. return;
  2911. }
  2912. packet.pending = true;
  2913. packet.tryCount++;
  2914. this.flags = packet.flags;
  2915. this.emit.apply(this, packet.args);
  2916. }
  2917. /**
  2918. * Sends a packet.
  2919. *
  2920. * @param packet
  2921. * @private
  2922. */
  2923. }, {
  2924. key: "packet",
  2925. value: function packet(_packet) {
  2926. _packet.nsp = this.nsp;
  2927. this.io._packet(_packet);
  2928. }
  2929. /**
  2930. * Called upon engine `open`.
  2931. *
  2932. * @private
  2933. */
  2934. }, {
  2935. key: "onopen",
  2936. value: function onopen() {
  2937. var _this5 = this;
  2938. if (typeof this.auth == "function") {
  2939. this.auth(function (data) {
  2940. _this5._sendConnectPacket(data);
  2941. });
  2942. } else {
  2943. this._sendConnectPacket(this.auth);
  2944. }
  2945. }
  2946. /**
  2947. * Sends a CONNECT packet to initiate the Socket.IO session.
  2948. *
  2949. * @param data
  2950. * @private
  2951. */
  2952. }, {
  2953. key: "_sendConnectPacket",
  2954. value: function _sendConnectPacket(data) {
  2955. this.packet({
  2956. type: PacketType.CONNECT,
  2957. data: this._pid ? _extends({
  2958. pid: this._pid,
  2959. offset: this._lastOffset
  2960. }, data) : data
  2961. });
  2962. }
  2963. /**
  2964. * Called upon engine or manager `error`.
  2965. *
  2966. * @param err
  2967. * @private
  2968. */
  2969. }, {
  2970. key: "onerror",
  2971. value: function onerror(err) {
  2972. if (!this.connected) {
  2973. this.emitReserved("connect_error", err);
  2974. }
  2975. }
  2976. /**
  2977. * Called upon engine `close`.
  2978. *
  2979. * @param reason
  2980. * @param description
  2981. * @private
  2982. */
  2983. }, {
  2984. key: "onclose",
  2985. value: function onclose(reason, description) {
  2986. this.connected = false;
  2987. delete this.id;
  2988. this.emitReserved("disconnect", reason, description);
  2989. }
  2990. /**
  2991. * Called with socket packet.
  2992. *
  2993. * @param packet
  2994. * @private
  2995. */
  2996. }, {
  2997. key: "onpacket",
  2998. value: function onpacket(packet) {
  2999. var sameNamespace = packet.nsp === this.nsp;
  3000. if (!sameNamespace) return;
  3001. switch (packet.type) {
  3002. case PacketType.CONNECT:
  3003. if (packet.data && packet.data.sid) {
  3004. this.onconnect(packet.data.sid, packet.data.pid);
  3005. } else {
  3006. 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/)"));
  3007. }
  3008. break;
  3009. case PacketType.EVENT:
  3010. case PacketType.BINARY_EVENT:
  3011. this.onevent(packet);
  3012. break;
  3013. case PacketType.ACK:
  3014. case PacketType.BINARY_ACK:
  3015. this.onack(packet);
  3016. break;
  3017. case PacketType.DISCONNECT:
  3018. this.ondisconnect();
  3019. break;
  3020. case PacketType.CONNECT_ERROR:
  3021. this.destroy();
  3022. var err = new Error(packet.data.message); // @ts-ignore
  3023. err.data = packet.data.data;
  3024. this.emitReserved("connect_error", err);
  3025. break;
  3026. }
  3027. }
  3028. /**
  3029. * Called upon a server event.
  3030. *
  3031. * @param packet
  3032. * @private
  3033. */
  3034. }, {
  3035. key: "onevent",
  3036. value: function onevent(packet) {
  3037. var args = packet.data || [];
  3038. if (null != packet.id) {
  3039. args.push(this.ack(packet.id));
  3040. }
  3041. if (this.connected) {
  3042. this.emitEvent(args);
  3043. } else {
  3044. this.receiveBuffer.push(Object.freeze(args));
  3045. }
  3046. }
  3047. }, {
  3048. key: "emitEvent",
  3049. value: function emitEvent(args) {
  3050. if (this._anyListeners && this._anyListeners.length) {
  3051. var listeners = this._anyListeners.slice();
  3052. var _iterator = _createForOfIteratorHelper(listeners),
  3053. _step;
  3054. try {
  3055. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  3056. var listener = _step.value;
  3057. listener.apply(this, args);
  3058. }
  3059. } catch (err) {
  3060. _iterator.e(err);
  3061. } finally {
  3062. _iterator.f();
  3063. }
  3064. }
  3065. _get(_getPrototypeOf(Socket.prototype), "emit", this).apply(this, args);
  3066. if (this._pid && args.length && typeof args[args.length - 1] === "string") {
  3067. this._lastOffset = args[args.length - 1];
  3068. }
  3069. }
  3070. /**
  3071. * Produces an ack callback to emit with an event.
  3072. *
  3073. * @private
  3074. */
  3075. }, {
  3076. key: "ack",
  3077. value: function ack(id) {
  3078. var self = this;
  3079. var sent = false;
  3080. return function () {
  3081. // prevent double callbacks
  3082. if (sent) return;
  3083. sent = true;
  3084. for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
  3085. args[_key6] = arguments[_key6];
  3086. }
  3087. self.packet({
  3088. type: PacketType.ACK,
  3089. id: id,
  3090. data: args
  3091. });
  3092. };
  3093. }
  3094. /**
  3095. * Called upon a server acknowlegement.
  3096. *
  3097. * @param packet
  3098. * @private
  3099. */
  3100. }, {
  3101. key: "onack",
  3102. value: function onack(packet) {
  3103. var ack = this.acks[packet.id];
  3104. if ("function" === typeof ack) {
  3105. ack.apply(this, packet.data);
  3106. delete this.acks[packet.id];
  3107. }
  3108. }
  3109. /**
  3110. * Called upon server connect.
  3111. *
  3112. * @private
  3113. */
  3114. }, {
  3115. key: "onconnect",
  3116. value: function onconnect(id, pid) {
  3117. this.id = id;
  3118. this.recovered = pid && this._pid === pid;
  3119. this._pid = pid; // defined only if connection state recovery is enabled
  3120. this.connected = true;
  3121. this.emitBuffered();
  3122. this.emitReserved("connect");
  3123. this._drainQueue(true);
  3124. }
  3125. /**
  3126. * Emit buffered events (received and emitted).
  3127. *
  3128. * @private
  3129. */
  3130. }, {
  3131. key: "emitBuffered",
  3132. value: function emitBuffered() {
  3133. var _this6 = this;
  3134. this.receiveBuffer.forEach(function (args) {
  3135. return _this6.emitEvent(args);
  3136. });
  3137. this.receiveBuffer = [];
  3138. this.sendBuffer.forEach(function (packet) {
  3139. _this6.notifyOutgoingListeners(packet);
  3140. _this6.packet(packet);
  3141. });
  3142. this.sendBuffer = [];
  3143. }
  3144. /**
  3145. * Called upon server disconnect.
  3146. *
  3147. * @private
  3148. */
  3149. }, {
  3150. key: "ondisconnect",
  3151. value: function ondisconnect() {
  3152. this.destroy();
  3153. this.onclose("io server disconnect");
  3154. }
  3155. /**
  3156. * Called upon forced client/server side disconnections,
  3157. * this method ensures the manager stops tracking us and
  3158. * that reconnections don't get triggered for this.
  3159. *
  3160. * @private
  3161. */
  3162. }, {
  3163. key: "destroy",
  3164. value: function destroy() {
  3165. if (this.subs) {
  3166. // clean subscriptions to avoid reconnections
  3167. this.subs.forEach(function (subDestroy) {
  3168. return subDestroy();
  3169. });
  3170. this.subs = undefined;
  3171. }
  3172. this.io["_destroy"](this);
  3173. }
  3174. /**
  3175. * Disconnects the socket manually. In that case, the socket will not try to reconnect.
  3176. *
  3177. * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
  3178. *
  3179. * @example
  3180. * const socket = io();
  3181. *
  3182. * socket.on("disconnect", (reason) => {
  3183. * // console.log(reason); prints "io client disconnect"
  3184. * });
  3185. *
  3186. * socket.disconnect();
  3187. *
  3188. * @return self
  3189. */
  3190. }, {
  3191. key: "disconnect",
  3192. value: function disconnect() {
  3193. if (this.connected) {
  3194. this.packet({
  3195. type: PacketType.DISCONNECT
  3196. });
  3197. } // remove socket from pool
  3198. this.destroy();
  3199. if (this.connected) {
  3200. // fire events
  3201. this.onclose("io client disconnect");
  3202. }
  3203. return this;
  3204. }
  3205. /**
  3206. * Alias for {@link disconnect()}.
  3207. *
  3208. * @return self
  3209. */
  3210. }, {
  3211. key: "close",
  3212. value: function close() {
  3213. return this.disconnect();
  3214. }
  3215. /**
  3216. * Sets the compress flag.
  3217. *
  3218. * @example
  3219. * socket.compress(false).emit("hello");
  3220. *
  3221. * @param compress - if `true`, compresses the sending data
  3222. * @return self
  3223. */
  3224. }, {
  3225. key: "compress",
  3226. value: function compress(_compress) {
  3227. this.flags.compress = _compress;
  3228. return this;
  3229. }
  3230. /**
  3231. * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
  3232. * ready to send messages.
  3233. *
  3234. * @example
  3235. * socket.volatile.emit("hello"); // the server may or may not receive it
  3236. *
  3237. * @returns self
  3238. */
  3239. }, {
  3240. key: "volatile",
  3241. get: function get() {
  3242. this.flags["volatile"] = true;
  3243. return this;
  3244. }
  3245. /**
  3246. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  3247. * given number of milliseconds have elapsed without an acknowledgement from the server:
  3248. *
  3249. * @example
  3250. * socket.timeout(5000).emit("my-event", (err) => {
  3251. * if (err) {
  3252. * // the server did not acknowledge the event in the given delay
  3253. * }
  3254. * });
  3255. *
  3256. * @returns self
  3257. */
  3258. }, {
  3259. key: "timeout",
  3260. value: function timeout(_timeout) {
  3261. this.flags.timeout = _timeout;
  3262. return this;
  3263. }
  3264. /**
  3265. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3266. * callback.
  3267. *
  3268. * @example
  3269. * socket.onAny((event, ...args) => {
  3270. * console.log(`got ${event}`);
  3271. * });
  3272. *
  3273. * @param listener
  3274. */
  3275. }, {
  3276. key: "onAny",
  3277. value: function onAny(listener) {
  3278. this._anyListeners = this._anyListeners || [];
  3279. this._anyListeners.push(listener);
  3280. return this;
  3281. }
  3282. /**
  3283. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3284. * callback. The listener is added to the beginning of the listeners array.
  3285. *
  3286. * @example
  3287. * socket.prependAny((event, ...args) => {
  3288. * console.log(`got event ${event}`);
  3289. * });
  3290. *
  3291. * @param listener
  3292. */
  3293. }, {
  3294. key: "prependAny",
  3295. value: function prependAny(listener) {
  3296. this._anyListeners = this._anyListeners || [];
  3297. this._anyListeners.unshift(listener);
  3298. return this;
  3299. }
  3300. /**
  3301. * Removes the listener that will be fired when any event is emitted.
  3302. *
  3303. * @example
  3304. * const catchAllListener = (event, ...args) => {
  3305. * console.log(`got event ${event}`);
  3306. * }
  3307. *
  3308. * socket.onAny(catchAllListener);
  3309. *
  3310. * // remove a specific listener
  3311. * socket.offAny(catchAllListener);
  3312. *
  3313. * // or remove all listeners
  3314. * socket.offAny();
  3315. *
  3316. * @param listener
  3317. */
  3318. }, {
  3319. key: "offAny",
  3320. value: function offAny(listener) {
  3321. if (!this._anyListeners) {
  3322. return this;
  3323. }
  3324. if (listener) {
  3325. var listeners = this._anyListeners;
  3326. for (var i = 0; i < listeners.length; i++) {
  3327. if (listener === listeners[i]) {
  3328. listeners.splice(i, 1);
  3329. return this;
  3330. }
  3331. }
  3332. } else {
  3333. this._anyListeners = [];
  3334. }
  3335. return this;
  3336. }
  3337. /**
  3338. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  3339. * e.g. to remove listeners.
  3340. */
  3341. }, {
  3342. key: "listenersAny",
  3343. value: function listenersAny() {
  3344. return this._anyListeners || [];
  3345. }
  3346. /**
  3347. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3348. * callback.
  3349. *
  3350. * Note: acknowledgements sent to the server are not included.
  3351. *
  3352. * @example
  3353. * socket.onAnyOutgoing((event, ...args) => {
  3354. * console.log(`sent event ${event}`);
  3355. * });
  3356. *
  3357. * @param listener
  3358. */
  3359. }, {
  3360. key: "onAnyOutgoing",
  3361. value: function onAnyOutgoing(listener) {
  3362. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  3363. this._anyOutgoingListeners.push(listener);
  3364. return this;
  3365. }
  3366. /**
  3367. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3368. * callback. The listener is added to the beginning of the listeners array.
  3369. *
  3370. * Note: acknowledgements sent to the server are not included.
  3371. *
  3372. * @example
  3373. * socket.prependAnyOutgoing((event, ...args) => {
  3374. * console.log(`sent event ${event}`);
  3375. * });
  3376. *
  3377. * @param listener
  3378. */
  3379. }, {
  3380. key: "prependAnyOutgoing",
  3381. value: function prependAnyOutgoing(listener) {
  3382. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  3383. this._anyOutgoingListeners.unshift(listener);
  3384. return this;
  3385. }
  3386. /**
  3387. * Removes the listener that will be fired when any event is emitted.
  3388. *
  3389. * @example
  3390. * const catchAllListener = (event, ...args) => {
  3391. * console.log(`sent event ${event}`);
  3392. * }
  3393. *
  3394. * socket.onAnyOutgoing(catchAllListener);
  3395. *
  3396. * // remove a specific listener
  3397. * socket.offAnyOutgoing(catchAllListener);
  3398. *
  3399. * // or remove all listeners
  3400. * socket.offAnyOutgoing();
  3401. *
  3402. * @param [listener] - the catch-all listener (optional)
  3403. */
  3404. }, {
  3405. key: "offAnyOutgoing",
  3406. value: function offAnyOutgoing(listener) {
  3407. if (!this._anyOutgoingListeners) {
  3408. return this;
  3409. }
  3410. if (listener) {
  3411. var listeners = this._anyOutgoingListeners;
  3412. for (var i = 0; i < listeners.length; i++) {
  3413. if (listener === listeners[i]) {
  3414. listeners.splice(i, 1);
  3415. return this;
  3416. }
  3417. }
  3418. } else {
  3419. this._anyOutgoingListeners = [];
  3420. }
  3421. return this;
  3422. }
  3423. /**
  3424. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  3425. * e.g. to remove listeners.
  3426. */
  3427. }, {
  3428. key: "listenersAnyOutgoing",
  3429. value: function listenersAnyOutgoing() {
  3430. return this._anyOutgoingListeners || [];
  3431. }
  3432. /**
  3433. * Notify the listeners for each packet sent
  3434. *
  3435. * @param packet
  3436. *
  3437. * @private
  3438. */
  3439. }, {
  3440. key: "notifyOutgoingListeners",
  3441. value: function notifyOutgoingListeners(packet) {
  3442. if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
  3443. var listeners = this._anyOutgoingListeners.slice();
  3444. var _iterator2 = _createForOfIteratorHelper(listeners),
  3445. _step2;
  3446. try {
  3447. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  3448. var listener = _step2.value;
  3449. listener.apply(this, packet.data);
  3450. }
  3451. } catch (err) {
  3452. _iterator2.e(err);
  3453. } finally {
  3454. _iterator2.f();
  3455. }
  3456. }
  3457. }
  3458. }]);
  3459. return Socket;
  3460. }(Emitter);
  3461. /**
  3462. * Initialize backoff timer with `opts`.
  3463. *
  3464. * - `min` initial timeout in milliseconds [100]
  3465. * - `max` max timeout [10000]
  3466. * - `jitter` [0]
  3467. * - `factor` [2]
  3468. *
  3469. * @param {Object} opts
  3470. * @api public
  3471. */
  3472. function Backoff(opts) {
  3473. opts = opts || {};
  3474. this.ms = opts.min || 100;
  3475. this.max = opts.max || 10000;
  3476. this.factor = opts.factor || 2;
  3477. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  3478. this.attempts = 0;
  3479. }
  3480. /**
  3481. * Return the backoff duration.
  3482. *
  3483. * @return {Number}
  3484. * @api public
  3485. */
  3486. Backoff.prototype.duration = function () {
  3487. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  3488. if (this.jitter) {
  3489. var rand = Math.random();
  3490. var deviation = Math.floor(rand * this.jitter * ms);
  3491. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  3492. }
  3493. return Math.min(ms, this.max) | 0;
  3494. };
  3495. /**
  3496. * Reset the number of attempts.
  3497. *
  3498. * @api public
  3499. */
  3500. Backoff.prototype.reset = function () {
  3501. this.attempts = 0;
  3502. };
  3503. /**
  3504. * Set the minimum duration
  3505. *
  3506. * @api public
  3507. */
  3508. Backoff.prototype.setMin = function (min) {
  3509. this.ms = min;
  3510. };
  3511. /**
  3512. * Set the maximum duration
  3513. *
  3514. * @api public
  3515. */
  3516. Backoff.prototype.setMax = function (max) {
  3517. this.max = max;
  3518. };
  3519. /**
  3520. * Set the jitter
  3521. *
  3522. * @api public
  3523. */
  3524. Backoff.prototype.setJitter = function (jitter) {
  3525. this.jitter = jitter;
  3526. };
  3527. var Manager = /*#__PURE__*/function (_Emitter) {
  3528. _inherits(Manager, _Emitter);
  3529. var _super = _createSuper(Manager);
  3530. function Manager(uri, opts) {
  3531. var _this;
  3532. _classCallCheck(this, Manager);
  3533. var _a;
  3534. _this = _super.call(this);
  3535. _this.nsps = {};
  3536. _this.subs = [];
  3537. if (uri && "object" === _typeof(uri)) {
  3538. opts = uri;
  3539. uri = undefined;
  3540. }
  3541. opts = opts || {};
  3542. opts.path = opts.path || "/socket.io";
  3543. _this.opts = opts;
  3544. installTimerFunctions(_assertThisInitialized(_this), opts);
  3545. _this.reconnection(opts.reconnection !== false);
  3546. _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  3547. _this.reconnectionDelay(opts.reconnectionDelay || 1000);
  3548. _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  3549. _this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
  3550. _this.backoff = new Backoff({
  3551. min: _this.reconnectionDelay(),
  3552. max: _this.reconnectionDelayMax(),
  3553. jitter: _this.randomizationFactor()
  3554. });
  3555. _this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  3556. _this._readyState = "closed";
  3557. _this.uri = uri;
  3558. var _parser = opts.parser || parser;
  3559. _this.encoder = new _parser.Encoder();
  3560. _this.decoder = new _parser.Decoder();
  3561. _this._autoConnect = opts.autoConnect !== false;
  3562. if (_this._autoConnect) _this.open();
  3563. return _this;
  3564. }
  3565. _createClass(Manager, [{
  3566. key: "reconnection",
  3567. value: function reconnection(v) {
  3568. if (!arguments.length) return this._reconnection;
  3569. this._reconnection = !!v;
  3570. return this;
  3571. }
  3572. }, {
  3573. key: "reconnectionAttempts",
  3574. value: function reconnectionAttempts(v) {
  3575. if (v === undefined) return this._reconnectionAttempts;
  3576. this._reconnectionAttempts = v;
  3577. return this;
  3578. }
  3579. }, {
  3580. key: "reconnectionDelay",
  3581. value: function reconnectionDelay(v) {
  3582. var _a;
  3583. if (v === undefined) return this._reconnectionDelay;
  3584. this._reconnectionDelay = v;
  3585. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
  3586. return this;
  3587. }
  3588. }, {
  3589. key: "randomizationFactor",
  3590. value: function randomizationFactor(v) {
  3591. var _a;
  3592. if (v === undefined) return this._randomizationFactor;
  3593. this._randomizationFactor = v;
  3594. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
  3595. return this;
  3596. }
  3597. }, {
  3598. key: "reconnectionDelayMax",
  3599. value: function reconnectionDelayMax(v) {
  3600. var _a;
  3601. if (v === undefined) return this._reconnectionDelayMax;
  3602. this._reconnectionDelayMax = v;
  3603. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
  3604. return this;
  3605. }
  3606. }, {
  3607. key: "timeout",
  3608. value: function timeout(v) {
  3609. if (!arguments.length) return this._timeout;
  3610. this._timeout = v;
  3611. return this;
  3612. }
  3613. /**
  3614. * Starts trying to reconnect if reconnection is enabled and we have not
  3615. * started reconnecting yet
  3616. *
  3617. * @private
  3618. */
  3619. }, {
  3620. key: "maybeReconnectOnOpen",
  3621. value: function maybeReconnectOnOpen() {
  3622. // Only try to reconnect if it's the first time we're connecting
  3623. if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
  3624. // keeps reconnection from firing twice for the same reconnection loop
  3625. this.reconnect();
  3626. }
  3627. }
  3628. /**
  3629. * Sets the current transport `socket`.
  3630. *
  3631. * @param {Function} fn - optional, callback
  3632. * @return self
  3633. * @public
  3634. */
  3635. }, {
  3636. key: "open",
  3637. value: function open(fn) {
  3638. var _this2 = this;
  3639. if (~this._readyState.indexOf("open")) return this;
  3640. this.engine = new Socket$1(this.uri, this.opts);
  3641. var socket = this.engine;
  3642. var self = this;
  3643. this._readyState = "opening";
  3644. this.skipReconnect = false; // emit `open`
  3645. var openSubDestroy = on(socket, "open", function () {
  3646. self.onopen();
  3647. fn && fn();
  3648. }); // emit `error`
  3649. var errorSub = on(socket, "error", function (err) {
  3650. self.cleanup();
  3651. self._readyState = "closed";
  3652. _this2.emitReserved("error", err);
  3653. if (fn) {
  3654. fn(err);
  3655. } else {
  3656. // Only do this if there is no fn to handle the error
  3657. self.maybeReconnectOnOpen();
  3658. }
  3659. });
  3660. if (false !== this._timeout) {
  3661. var timeout = this._timeout;
  3662. if (timeout === 0) {
  3663. openSubDestroy(); // prevents a race condition with the 'open' event
  3664. } // set timer
  3665. var timer = this.setTimeoutFn(function () {
  3666. openSubDestroy();
  3667. socket.close(); // @ts-ignore
  3668. socket.emit("error", new Error("timeout"));
  3669. }, timeout);
  3670. if (this.opts.autoUnref) {
  3671. timer.unref();
  3672. }
  3673. this.subs.push(function subDestroy() {
  3674. clearTimeout(timer);
  3675. });
  3676. }
  3677. this.subs.push(openSubDestroy);
  3678. this.subs.push(errorSub);
  3679. return this;
  3680. }
  3681. /**
  3682. * Alias for open()
  3683. *
  3684. * @return self
  3685. * @public
  3686. */
  3687. }, {
  3688. key: "connect",
  3689. value: function connect(fn) {
  3690. return this.open(fn);
  3691. }
  3692. /**
  3693. * Called upon transport open.
  3694. *
  3695. * @private
  3696. */
  3697. }, {
  3698. key: "onopen",
  3699. value: function onopen() {
  3700. // clear old subs
  3701. this.cleanup(); // mark as open
  3702. this._readyState = "open";
  3703. this.emitReserved("open"); // add new subs
  3704. var socket = this.engine;
  3705. 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)));
  3706. }
  3707. /**
  3708. * Called upon a ping.
  3709. *
  3710. * @private
  3711. */
  3712. }, {
  3713. key: "onping",
  3714. value: function onping() {
  3715. this.emitReserved("ping");
  3716. }
  3717. /**
  3718. * Called with data.
  3719. *
  3720. * @private
  3721. */
  3722. }, {
  3723. key: "ondata",
  3724. value: function ondata(data) {
  3725. try {
  3726. this.decoder.add(data);
  3727. } catch (e) {
  3728. this.onclose("parse error", e);
  3729. }
  3730. }
  3731. /**
  3732. * Called when parser fully decodes a packet.
  3733. *
  3734. * @private
  3735. */
  3736. }, {
  3737. key: "ondecoded",
  3738. value: function ondecoded(packet) {
  3739. var _this3 = this;
  3740. // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
  3741. nextTick(function () {
  3742. _this3.emitReserved("packet", packet);
  3743. }, this.setTimeoutFn);
  3744. }
  3745. /**
  3746. * Called upon socket error.
  3747. *
  3748. * @private
  3749. */
  3750. }, {
  3751. key: "onerror",
  3752. value: function onerror(err) {
  3753. this.emitReserved("error", err);
  3754. }
  3755. /**
  3756. * Creates a new socket for the given `nsp`.
  3757. *
  3758. * @return {Socket}
  3759. * @public
  3760. */
  3761. }, {
  3762. key: "socket",
  3763. value: function socket(nsp, opts) {
  3764. var socket = this.nsps[nsp];
  3765. if (!socket) {
  3766. socket = new Socket(this, nsp, opts);
  3767. this.nsps[nsp] = socket;
  3768. } else if (this._autoConnect && !socket.active) {
  3769. socket.connect();
  3770. }
  3771. return socket;
  3772. }
  3773. /**
  3774. * Called upon a socket close.
  3775. *
  3776. * @param socket
  3777. * @private
  3778. */
  3779. }, {
  3780. key: "_destroy",
  3781. value: function _destroy(socket) {
  3782. var nsps = Object.keys(this.nsps);
  3783. for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) {
  3784. var nsp = _nsps[_i];
  3785. var _socket = this.nsps[nsp];
  3786. if (_socket.active) {
  3787. return;
  3788. }
  3789. }
  3790. this._close();
  3791. }
  3792. /**
  3793. * Writes a packet.
  3794. *
  3795. * @param packet
  3796. * @private
  3797. */
  3798. }, {
  3799. key: "_packet",
  3800. value: function _packet(packet) {
  3801. var encodedPackets = this.encoder.encode(packet);
  3802. for (var i = 0; i < encodedPackets.length; i++) {
  3803. this.engine.write(encodedPackets[i], packet.options);
  3804. }
  3805. }
  3806. /**
  3807. * Clean up transport subscriptions and packet buffer.
  3808. *
  3809. * @private
  3810. */
  3811. }, {
  3812. key: "cleanup",
  3813. value: function cleanup() {
  3814. this.subs.forEach(function (subDestroy) {
  3815. return subDestroy();
  3816. });
  3817. this.subs.length = 0;
  3818. this.decoder.destroy();
  3819. }
  3820. /**
  3821. * Close the current socket.
  3822. *
  3823. * @private
  3824. */
  3825. }, {
  3826. key: "_close",
  3827. value: function _close() {
  3828. this.skipReconnect = true;
  3829. this._reconnecting = false;
  3830. this.onclose("forced close");
  3831. if (this.engine) this.engine.close();
  3832. }
  3833. /**
  3834. * Alias for close()
  3835. *
  3836. * @private
  3837. */
  3838. }, {
  3839. key: "disconnect",
  3840. value: function disconnect() {
  3841. return this._close();
  3842. }
  3843. /**
  3844. * Called upon engine close.
  3845. *
  3846. * @private
  3847. */
  3848. }, {
  3849. key: "onclose",
  3850. value: function onclose(reason, description) {
  3851. this.cleanup();
  3852. this.backoff.reset();
  3853. this._readyState = "closed";
  3854. this.emitReserved("close", reason, description);
  3855. if (this._reconnection && !this.skipReconnect) {
  3856. this.reconnect();
  3857. }
  3858. }
  3859. /**
  3860. * Attempt a reconnection.
  3861. *
  3862. * @private
  3863. */
  3864. }, {
  3865. key: "reconnect",
  3866. value: function reconnect() {
  3867. var _this4 = this;
  3868. if (this._reconnecting || this.skipReconnect) return this;
  3869. var self = this;
  3870. if (this.backoff.attempts >= this._reconnectionAttempts) {
  3871. this.backoff.reset();
  3872. this.emitReserved("reconnect_failed");
  3873. this._reconnecting = false;
  3874. } else {
  3875. var delay = this.backoff.duration();
  3876. this._reconnecting = true;
  3877. var timer = this.setTimeoutFn(function () {
  3878. if (self.skipReconnect) return;
  3879. _this4.emitReserved("reconnect_attempt", self.backoff.attempts); // check again for the case socket closed in above events
  3880. if (self.skipReconnect) return;
  3881. self.open(function (err) {
  3882. if (err) {
  3883. self._reconnecting = false;
  3884. self.reconnect();
  3885. _this4.emitReserved("reconnect_error", err);
  3886. } else {
  3887. self.onreconnect();
  3888. }
  3889. });
  3890. }, delay);
  3891. if (this.opts.autoUnref) {
  3892. timer.unref();
  3893. }
  3894. this.subs.push(function subDestroy() {
  3895. clearTimeout(timer);
  3896. });
  3897. }
  3898. }
  3899. /**
  3900. * Called upon successful reconnect.
  3901. *
  3902. * @private
  3903. */
  3904. }, {
  3905. key: "onreconnect",
  3906. value: function onreconnect() {
  3907. var attempt = this.backoff.attempts;
  3908. this._reconnecting = false;
  3909. this.backoff.reset();
  3910. this.emitReserved("reconnect", attempt);
  3911. }
  3912. }]);
  3913. return Manager;
  3914. }(Emitter);
  3915. /**
  3916. * Managers cache.
  3917. */
  3918. var cache = {};
  3919. function lookup(uri, opts) {
  3920. if (_typeof(uri) === "object") {
  3921. opts = uri;
  3922. uri = undefined;
  3923. }
  3924. opts = opts || {};
  3925. var parsed = url(uri, opts.path || "/socket.io");
  3926. var source = parsed.source;
  3927. var id = parsed.id;
  3928. var path = parsed.path;
  3929. var sameNamespace = cache[id] && path in cache[id]["nsps"];
  3930. var newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
  3931. var io;
  3932. if (newConnection) {
  3933. io = new Manager(source, opts);
  3934. } else {
  3935. if (!cache[id]) {
  3936. cache[id] = new Manager(source, opts);
  3937. }
  3938. io = cache[id];
  3939. }
  3940. if (parsed.query && !opts.query) {
  3941. opts.query = parsed.queryKey;
  3942. }
  3943. return io.socket(parsed.path, opts);
  3944. } // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
  3945. // namespace (e.g. `io.connect(...)`), for backward compatibility
  3946. _extends(lookup, {
  3947. Manager: Manager,
  3948. Socket: Socket,
  3949. io: lookup,
  3950. connect: lookup
  3951. });
  3952. return lookup;
  3953. }));
  3954. //# sourceMappingURL=socket.io.js.map