socket.io.js 132 KB

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