Node-Red configuration
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

socket.io.js 133KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437
  1. /*!
  2. * Socket.IO v4.7.5
  3. * (c) 2014-2024 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. /**
  2971. * A map containing acknowledgement handlers.
  2972. *
  2973. * The `withError` attribute is used to differentiate handlers that accept an error as first argument:
  2974. *
  2975. * - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
  2976. * - `socket.timeout(5000).emit("test", (err, value) => { ... })`
  2977. * - `const value = await socket.emitWithAck("test")`
  2978. *
  2979. * From those that don't:
  2980. *
  2981. * - `socket.emit("test", (value) => { ... });`
  2982. *
  2983. * In the first case, the handlers will be called with an error when:
  2984. *
  2985. * - the timeout is reached
  2986. * - the socket gets disconnected
  2987. *
  2988. * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
  2989. * an acknowledgement from the server.
  2990. *
  2991. * @private
  2992. */
  2993. _this.acks = {};
  2994. _this.flags = {};
  2995. _this.io = io;
  2996. _this.nsp = nsp;
  2997. if (opts && opts.auth) {
  2998. _this.auth = opts.auth;
  2999. }
  3000. _this._opts = _extends({}, opts);
  3001. if (_this.io._autoConnect) _this.open();
  3002. return _this;
  3003. }
  3004. /**
  3005. * Whether the socket is currently disconnected
  3006. *
  3007. * @example
  3008. * const socket = io();
  3009. *
  3010. * socket.on("connect", () => {
  3011. * console.log(socket.disconnected); // false
  3012. * });
  3013. *
  3014. * socket.on("disconnect", () => {
  3015. * console.log(socket.disconnected); // true
  3016. * });
  3017. */
  3018. _createClass(Socket, [{
  3019. key: "disconnected",
  3020. get: function get() {
  3021. return !this.connected;
  3022. }
  3023. /**
  3024. * Subscribe to open, close and packet events
  3025. *
  3026. * @private
  3027. */
  3028. }, {
  3029. key: "subEvents",
  3030. value: function subEvents() {
  3031. if (this.subs) return;
  3032. var io = this.io;
  3033. 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))];
  3034. }
  3035. /**
  3036. * Whether the Socket will try to reconnect when its Manager connects or reconnects.
  3037. *
  3038. * @example
  3039. * const socket = io();
  3040. *
  3041. * console.log(socket.active); // true
  3042. *
  3043. * socket.on("disconnect", (reason) => {
  3044. * if (reason === "io server disconnect") {
  3045. * // the disconnection was initiated by the server, you need to manually reconnect
  3046. * console.log(socket.active); // false
  3047. * }
  3048. * // else the socket will automatically try to reconnect
  3049. * console.log(socket.active); // true
  3050. * });
  3051. */
  3052. }, {
  3053. key: "active",
  3054. get: function get() {
  3055. return !!this.subs;
  3056. }
  3057. /**
  3058. * "Opens" the socket.
  3059. *
  3060. * @example
  3061. * const socket = io({
  3062. * autoConnect: false
  3063. * });
  3064. *
  3065. * socket.connect();
  3066. */
  3067. }, {
  3068. key: "connect",
  3069. value: function connect() {
  3070. if (this.connected) return this;
  3071. this.subEvents();
  3072. if (!this.io["_reconnecting"]) this.io.open(); // ensure open
  3073. if ("open" === this.io._readyState) this.onopen();
  3074. return this;
  3075. }
  3076. /**
  3077. * Alias for {@link connect()}.
  3078. */
  3079. }, {
  3080. key: "open",
  3081. value: function open() {
  3082. return this.connect();
  3083. }
  3084. /**
  3085. * Sends a `message` event.
  3086. *
  3087. * This method mimics the WebSocket.send() method.
  3088. *
  3089. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  3090. *
  3091. * @example
  3092. * socket.send("hello");
  3093. *
  3094. * // this is equivalent to
  3095. * socket.emit("message", "hello");
  3096. *
  3097. * @return self
  3098. */
  3099. }, {
  3100. key: "send",
  3101. value: function send() {
  3102. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3103. args[_key] = arguments[_key];
  3104. }
  3105. args.unshift("message");
  3106. this.emit.apply(this, args);
  3107. return this;
  3108. }
  3109. /**
  3110. * Override `emit`.
  3111. * If the event is in `events`, it's emitted normally.
  3112. *
  3113. * @example
  3114. * socket.emit("hello", "world");
  3115. *
  3116. * // all serializable datastructures are supported (no need to call JSON.stringify)
  3117. * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
  3118. *
  3119. * // with an acknowledgement from the server
  3120. * socket.emit("hello", "world", (val) => {
  3121. * // ...
  3122. * });
  3123. *
  3124. * @return self
  3125. */
  3126. }, {
  3127. key: "emit",
  3128. value: function emit(ev) {
  3129. if (RESERVED_EVENTS.hasOwnProperty(ev)) {
  3130. throw new Error('"' + ev.toString() + '" is a reserved event name');
  3131. }
  3132. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  3133. args[_key2 - 1] = arguments[_key2];
  3134. }
  3135. args.unshift(ev);
  3136. if (this._opts.retries && !this.flags.fromQueue && !this.flags["volatile"]) {
  3137. this._addToQueue(args);
  3138. return this;
  3139. }
  3140. var packet = {
  3141. type: PacketType.EVENT,
  3142. data: args
  3143. };
  3144. packet.options = {};
  3145. packet.options.compress = this.flags.compress !== false;
  3146. // event ack callback
  3147. if ("function" === typeof args[args.length - 1]) {
  3148. var id = this.ids++;
  3149. var ack = args.pop();
  3150. this._registerAckCallback(id, ack);
  3151. packet.id = id;
  3152. }
  3153. var isTransportWritable = this.io.engine && this.io.engine.transport && this.io.engine.transport.writable;
  3154. var discardPacket = this.flags["volatile"] && (!isTransportWritable || !this.connected);
  3155. if (discardPacket) ; else if (this.connected) {
  3156. this.notifyOutgoingListeners(packet);
  3157. this.packet(packet);
  3158. } else {
  3159. this.sendBuffer.push(packet);
  3160. }
  3161. this.flags = {};
  3162. return this;
  3163. }
  3164. /**
  3165. * @private
  3166. */
  3167. }, {
  3168. key: "_registerAckCallback",
  3169. value: function _registerAckCallback(id, ack) {
  3170. var _this2 = this;
  3171. var _a;
  3172. var timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
  3173. if (timeout === undefined) {
  3174. this.acks[id] = ack;
  3175. return;
  3176. }
  3177. // @ts-ignore
  3178. var timer = this.io.setTimeoutFn(function () {
  3179. delete _this2.acks[id];
  3180. for (var i = 0; i < _this2.sendBuffer.length; i++) {
  3181. if (_this2.sendBuffer[i].id === id) {
  3182. _this2.sendBuffer.splice(i, 1);
  3183. }
  3184. }
  3185. ack.call(_this2, new Error("operation has timed out"));
  3186. }, timeout);
  3187. var fn = function fn() {
  3188. // @ts-ignore
  3189. _this2.io.clearTimeoutFn(timer);
  3190. for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  3191. args[_key3] = arguments[_key3];
  3192. }
  3193. ack.apply(_this2, args);
  3194. };
  3195. fn.withError = true;
  3196. this.acks[id] = fn;
  3197. }
  3198. /**
  3199. * Emits an event and waits for an acknowledgement
  3200. *
  3201. * @example
  3202. * // without timeout
  3203. * const response = await socket.emitWithAck("hello", "world");
  3204. *
  3205. * // with a specific timeout
  3206. * try {
  3207. * const response = await socket.timeout(1000).emitWithAck("hello", "world");
  3208. * } catch (err) {
  3209. * // the server did not acknowledge the event in the given delay
  3210. * }
  3211. *
  3212. * @return a Promise that will be fulfilled when the server acknowledges the event
  3213. */
  3214. }, {
  3215. key: "emitWithAck",
  3216. value: function emitWithAck(ev) {
  3217. var _this3 = this;
  3218. for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
  3219. args[_key4 - 1] = arguments[_key4];
  3220. }
  3221. return new Promise(function (resolve, reject) {
  3222. var fn = function fn(arg1, arg2) {
  3223. return arg1 ? reject(arg1) : resolve(arg2);
  3224. };
  3225. fn.withError = true;
  3226. args.push(fn);
  3227. _this3.emit.apply(_this3, [ev].concat(args));
  3228. });
  3229. }
  3230. /**
  3231. * Add the packet to the queue.
  3232. * @param args
  3233. * @private
  3234. */
  3235. }, {
  3236. key: "_addToQueue",
  3237. value: function _addToQueue(args) {
  3238. var _this4 = this;
  3239. var ack;
  3240. if (typeof args[args.length - 1] === "function") {
  3241. ack = args.pop();
  3242. }
  3243. var packet = {
  3244. id: this._queueSeq++,
  3245. tryCount: 0,
  3246. pending: false,
  3247. args: args,
  3248. flags: _extends({
  3249. fromQueue: true
  3250. }, this.flags)
  3251. };
  3252. args.push(function (err) {
  3253. if (packet !== _this4._queue[0]) {
  3254. // the packet has already been acknowledged
  3255. return;
  3256. }
  3257. var hasError = err !== null;
  3258. if (hasError) {
  3259. if (packet.tryCount > _this4._opts.retries) {
  3260. _this4._queue.shift();
  3261. if (ack) {
  3262. ack(err);
  3263. }
  3264. }
  3265. } else {
  3266. _this4._queue.shift();
  3267. if (ack) {
  3268. for (var _len5 = arguments.length, responseArgs = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
  3269. responseArgs[_key5 - 1] = arguments[_key5];
  3270. }
  3271. ack.apply(void 0, [null].concat(responseArgs));
  3272. }
  3273. }
  3274. packet.pending = false;
  3275. return _this4._drainQueue();
  3276. });
  3277. this._queue.push(packet);
  3278. this._drainQueue();
  3279. }
  3280. /**
  3281. * Send the first packet of the queue, and wait for an acknowledgement from the server.
  3282. * @param force - whether to resend a packet that has not been acknowledged yet
  3283. *
  3284. * @private
  3285. */
  3286. }, {
  3287. key: "_drainQueue",
  3288. value: function _drainQueue() {
  3289. var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  3290. if (!this.connected || this._queue.length === 0) {
  3291. return;
  3292. }
  3293. var packet = this._queue[0];
  3294. if (packet.pending && !force) {
  3295. return;
  3296. }
  3297. packet.pending = true;
  3298. packet.tryCount++;
  3299. this.flags = packet.flags;
  3300. this.emit.apply(this, packet.args);
  3301. }
  3302. /**
  3303. * Sends a packet.
  3304. *
  3305. * @param packet
  3306. * @private
  3307. */
  3308. }, {
  3309. key: "packet",
  3310. value: function packet(_packet) {
  3311. _packet.nsp = this.nsp;
  3312. this.io._packet(_packet);
  3313. }
  3314. /**
  3315. * Called upon engine `open`.
  3316. *
  3317. * @private
  3318. */
  3319. }, {
  3320. key: "onopen",
  3321. value: function onopen() {
  3322. var _this5 = this;
  3323. if (typeof this.auth == "function") {
  3324. this.auth(function (data) {
  3325. _this5._sendConnectPacket(data);
  3326. });
  3327. } else {
  3328. this._sendConnectPacket(this.auth);
  3329. }
  3330. }
  3331. /**
  3332. * Sends a CONNECT packet to initiate the Socket.IO session.
  3333. *
  3334. * @param data
  3335. * @private
  3336. */
  3337. }, {
  3338. key: "_sendConnectPacket",
  3339. value: function _sendConnectPacket(data) {
  3340. this.packet({
  3341. type: PacketType.CONNECT,
  3342. data: this._pid ? _extends({
  3343. pid: this._pid,
  3344. offset: this._lastOffset
  3345. }, data) : data
  3346. });
  3347. }
  3348. /**
  3349. * Called upon engine or manager `error`.
  3350. *
  3351. * @param err
  3352. * @private
  3353. */
  3354. }, {
  3355. key: "onerror",
  3356. value: function onerror(err) {
  3357. if (!this.connected) {
  3358. this.emitReserved("connect_error", err);
  3359. }
  3360. }
  3361. /**
  3362. * Called upon engine `close`.
  3363. *
  3364. * @param reason
  3365. * @param description
  3366. * @private
  3367. */
  3368. }, {
  3369. key: "onclose",
  3370. value: function onclose(reason, description) {
  3371. this.connected = false;
  3372. delete this.id;
  3373. this.emitReserved("disconnect", reason, description);
  3374. this._clearAcks();
  3375. }
  3376. /**
  3377. * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
  3378. * the server.
  3379. *
  3380. * @private
  3381. */
  3382. }, {
  3383. key: "_clearAcks",
  3384. value: function _clearAcks() {
  3385. var _this6 = this;
  3386. Object.keys(this.acks).forEach(function (id) {
  3387. var isBuffered = _this6.sendBuffer.some(function (packet) {
  3388. return String(packet.id) === id;
  3389. });
  3390. if (!isBuffered) {
  3391. // note: handlers that do not accept an error as first argument are ignored here
  3392. var ack = _this6.acks[id];
  3393. delete _this6.acks[id];
  3394. if (ack.withError) {
  3395. ack.call(_this6, new Error("socket has been disconnected"));
  3396. }
  3397. }
  3398. });
  3399. }
  3400. /**
  3401. * Called with socket packet.
  3402. *
  3403. * @param packet
  3404. * @private
  3405. */
  3406. }, {
  3407. key: "onpacket",
  3408. value: function onpacket(packet) {
  3409. var sameNamespace = packet.nsp === this.nsp;
  3410. if (!sameNamespace) return;
  3411. switch (packet.type) {
  3412. case PacketType.CONNECT:
  3413. if (packet.data && packet.data.sid) {
  3414. this.onconnect(packet.data.sid, packet.data.pid);
  3415. } else {
  3416. 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/)"));
  3417. }
  3418. break;
  3419. case PacketType.EVENT:
  3420. case PacketType.BINARY_EVENT:
  3421. this.onevent(packet);
  3422. break;
  3423. case PacketType.ACK:
  3424. case PacketType.BINARY_ACK:
  3425. this.onack(packet);
  3426. break;
  3427. case PacketType.DISCONNECT:
  3428. this.ondisconnect();
  3429. break;
  3430. case PacketType.CONNECT_ERROR:
  3431. this.destroy();
  3432. var err = new Error(packet.data.message);
  3433. // @ts-ignore
  3434. err.data = packet.data.data;
  3435. this.emitReserved("connect_error", err);
  3436. break;
  3437. }
  3438. }
  3439. /**
  3440. * Called upon a server event.
  3441. *
  3442. * @param packet
  3443. * @private
  3444. */
  3445. }, {
  3446. key: "onevent",
  3447. value: function onevent(packet) {
  3448. var args = packet.data || [];
  3449. if (null != packet.id) {
  3450. args.push(this.ack(packet.id));
  3451. }
  3452. if (this.connected) {
  3453. this.emitEvent(args);
  3454. } else {
  3455. this.receiveBuffer.push(Object.freeze(args));
  3456. }
  3457. }
  3458. }, {
  3459. key: "emitEvent",
  3460. value: function emitEvent(args) {
  3461. if (this._anyListeners && this._anyListeners.length) {
  3462. var listeners = this._anyListeners.slice();
  3463. var _iterator = _createForOfIteratorHelper(listeners),
  3464. _step;
  3465. try {
  3466. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  3467. var listener = _step.value;
  3468. listener.apply(this, args);
  3469. }
  3470. } catch (err) {
  3471. _iterator.e(err);
  3472. } finally {
  3473. _iterator.f();
  3474. }
  3475. }
  3476. _get(_getPrototypeOf(Socket.prototype), "emit", this).apply(this, args);
  3477. if (this._pid && args.length && typeof args[args.length - 1] === "string") {
  3478. this._lastOffset = args[args.length - 1];
  3479. }
  3480. }
  3481. /**
  3482. * Produces an ack callback to emit with an event.
  3483. *
  3484. * @private
  3485. */
  3486. }, {
  3487. key: "ack",
  3488. value: function ack(id) {
  3489. var self = this;
  3490. var sent = false;
  3491. return function () {
  3492. // prevent double callbacks
  3493. if (sent) return;
  3494. sent = true;
  3495. for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
  3496. args[_key6] = arguments[_key6];
  3497. }
  3498. self.packet({
  3499. type: PacketType.ACK,
  3500. id: id,
  3501. data: args
  3502. });
  3503. };
  3504. }
  3505. /**
  3506. * Called upon a server acknowledgement.
  3507. *
  3508. * @param packet
  3509. * @private
  3510. */
  3511. }, {
  3512. key: "onack",
  3513. value: function onack(packet) {
  3514. var ack = this.acks[packet.id];
  3515. if (typeof ack !== "function") {
  3516. return;
  3517. }
  3518. delete this.acks[packet.id];
  3519. // @ts-ignore FIXME ack is incorrectly inferred as 'never'
  3520. if (ack.withError) {
  3521. packet.data.unshift(null);
  3522. }
  3523. // @ts-ignore
  3524. ack.apply(this, packet.data);
  3525. }
  3526. /**
  3527. * Called upon server connect.
  3528. *
  3529. * @private
  3530. */
  3531. }, {
  3532. key: "onconnect",
  3533. value: function onconnect(id, pid) {
  3534. this.id = id;
  3535. this.recovered = pid && this._pid === pid;
  3536. this._pid = pid; // defined only if connection state recovery is enabled
  3537. this.connected = true;
  3538. this.emitBuffered();
  3539. this.emitReserved("connect");
  3540. this._drainQueue(true);
  3541. }
  3542. /**
  3543. * Emit buffered events (received and emitted).
  3544. *
  3545. * @private
  3546. */
  3547. }, {
  3548. key: "emitBuffered",
  3549. value: function emitBuffered() {
  3550. var _this7 = this;
  3551. this.receiveBuffer.forEach(function (args) {
  3552. return _this7.emitEvent(args);
  3553. });
  3554. this.receiveBuffer = [];
  3555. this.sendBuffer.forEach(function (packet) {
  3556. _this7.notifyOutgoingListeners(packet);
  3557. _this7.packet(packet);
  3558. });
  3559. this.sendBuffer = [];
  3560. }
  3561. /**
  3562. * Called upon server disconnect.
  3563. *
  3564. * @private
  3565. */
  3566. }, {
  3567. key: "ondisconnect",
  3568. value: function ondisconnect() {
  3569. this.destroy();
  3570. this.onclose("io server disconnect");
  3571. }
  3572. /**
  3573. * Called upon forced client/server side disconnections,
  3574. * this method ensures the manager stops tracking us and
  3575. * that reconnections don't get triggered for this.
  3576. *
  3577. * @private
  3578. */
  3579. }, {
  3580. key: "destroy",
  3581. value: function destroy() {
  3582. if (this.subs) {
  3583. // clean subscriptions to avoid reconnections
  3584. this.subs.forEach(function (subDestroy) {
  3585. return subDestroy();
  3586. });
  3587. this.subs = undefined;
  3588. }
  3589. this.io["_destroy"](this);
  3590. }
  3591. /**
  3592. * Disconnects the socket manually. In that case, the socket will not try to reconnect.
  3593. *
  3594. * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
  3595. *
  3596. * @example
  3597. * const socket = io();
  3598. *
  3599. * socket.on("disconnect", (reason) => {
  3600. * // console.log(reason); prints "io client disconnect"
  3601. * });
  3602. *
  3603. * socket.disconnect();
  3604. *
  3605. * @return self
  3606. */
  3607. }, {
  3608. key: "disconnect",
  3609. value: function disconnect() {
  3610. if (this.connected) {
  3611. this.packet({
  3612. type: PacketType.DISCONNECT
  3613. });
  3614. }
  3615. // remove socket from pool
  3616. this.destroy();
  3617. if (this.connected) {
  3618. // fire events
  3619. this.onclose("io client disconnect");
  3620. }
  3621. return this;
  3622. }
  3623. /**
  3624. * Alias for {@link disconnect()}.
  3625. *
  3626. * @return self
  3627. */
  3628. }, {
  3629. key: "close",
  3630. value: function close() {
  3631. return this.disconnect();
  3632. }
  3633. /**
  3634. * Sets the compress flag.
  3635. *
  3636. * @example
  3637. * socket.compress(false).emit("hello");
  3638. *
  3639. * @param compress - if `true`, compresses the sending data
  3640. * @return self
  3641. */
  3642. }, {
  3643. key: "compress",
  3644. value: function compress(_compress) {
  3645. this.flags.compress = _compress;
  3646. return this;
  3647. }
  3648. /**
  3649. * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
  3650. * ready to send messages.
  3651. *
  3652. * @example
  3653. * socket.volatile.emit("hello"); // the server may or may not receive it
  3654. *
  3655. * @returns self
  3656. */
  3657. }, {
  3658. key: "volatile",
  3659. get: function get() {
  3660. this.flags["volatile"] = true;
  3661. return this;
  3662. }
  3663. /**
  3664. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  3665. * given number of milliseconds have elapsed without an acknowledgement from the server:
  3666. *
  3667. * @example
  3668. * socket.timeout(5000).emit("my-event", (err) => {
  3669. * if (err) {
  3670. * // the server did not acknowledge the event in the given delay
  3671. * }
  3672. * });
  3673. *
  3674. * @returns self
  3675. */
  3676. }, {
  3677. key: "timeout",
  3678. value: function timeout(_timeout) {
  3679. this.flags.timeout = _timeout;
  3680. return this;
  3681. }
  3682. /**
  3683. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3684. * callback.
  3685. *
  3686. * @example
  3687. * socket.onAny((event, ...args) => {
  3688. * console.log(`got ${event}`);
  3689. * });
  3690. *
  3691. * @param listener
  3692. */
  3693. }, {
  3694. key: "onAny",
  3695. value: function onAny(listener) {
  3696. this._anyListeners = this._anyListeners || [];
  3697. this._anyListeners.push(listener);
  3698. return this;
  3699. }
  3700. /**
  3701. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3702. * callback. The listener is added to the beginning of the listeners array.
  3703. *
  3704. * @example
  3705. * socket.prependAny((event, ...args) => {
  3706. * console.log(`got event ${event}`);
  3707. * });
  3708. *
  3709. * @param listener
  3710. */
  3711. }, {
  3712. key: "prependAny",
  3713. value: function prependAny(listener) {
  3714. this._anyListeners = this._anyListeners || [];
  3715. this._anyListeners.unshift(listener);
  3716. return this;
  3717. }
  3718. /**
  3719. * Removes the listener that will be fired when any event is emitted.
  3720. *
  3721. * @example
  3722. * const catchAllListener = (event, ...args) => {
  3723. * console.log(`got event ${event}`);
  3724. * }
  3725. *
  3726. * socket.onAny(catchAllListener);
  3727. *
  3728. * // remove a specific listener
  3729. * socket.offAny(catchAllListener);
  3730. *
  3731. * // or remove all listeners
  3732. * socket.offAny();
  3733. *
  3734. * @param listener
  3735. */
  3736. }, {
  3737. key: "offAny",
  3738. value: function offAny(listener) {
  3739. if (!this._anyListeners) {
  3740. return this;
  3741. }
  3742. if (listener) {
  3743. var listeners = this._anyListeners;
  3744. for (var i = 0; i < listeners.length; i++) {
  3745. if (listener === listeners[i]) {
  3746. listeners.splice(i, 1);
  3747. return this;
  3748. }
  3749. }
  3750. } else {
  3751. this._anyListeners = [];
  3752. }
  3753. return this;
  3754. }
  3755. /**
  3756. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  3757. * e.g. to remove listeners.
  3758. */
  3759. }, {
  3760. key: "listenersAny",
  3761. value: function listenersAny() {
  3762. return this._anyListeners || [];
  3763. }
  3764. /**
  3765. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3766. * callback.
  3767. *
  3768. * Note: acknowledgements sent to the server are not included.
  3769. *
  3770. * @example
  3771. * socket.onAnyOutgoing((event, ...args) => {
  3772. * console.log(`sent event ${event}`);
  3773. * });
  3774. *
  3775. * @param listener
  3776. */
  3777. }, {
  3778. key: "onAnyOutgoing",
  3779. value: function onAnyOutgoing(listener) {
  3780. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  3781. this._anyOutgoingListeners.push(listener);
  3782. return this;
  3783. }
  3784. /**
  3785. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3786. * callback. The listener is added to the beginning of the listeners array.
  3787. *
  3788. * Note: acknowledgements sent to the server are not included.
  3789. *
  3790. * @example
  3791. * socket.prependAnyOutgoing((event, ...args) => {
  3792. * console.log(`sent event ${event}`);
  3793. * });
  3794. *
  3795. * @param listener
  3796. */
  3797. }, {
  3798. key: "prependAnyOutgoing",
  3799. value: function prependAnyOutgoing(listener) {
  3800. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  3801. this._anyOutgoingListeners.unshift(listener);
  3802. return this;
  3803. }
  3804. /**
  3805. * Removes the listener that will be fired when any event is emitted.
  3806. *
  3807. * @example
  3808. * const catchAllListener = (event, ...args) => {
  3809. * console.log(`sent event ${event}`);
  3810. * }
  3811. *
  3812. * socket.onAnyOutgoing(catchAllListener);
  3813. *
  3814. * // remove a specific listener
  3815. * socket.offAnyOutgoing(catchAllListener);
  3816. *
  3817. * // or remove all listeners
  3818. * socket.offAnyOutgoing();
  3819. *
  3820. * @param [listener] - the catch-all listener (optional)
  3821. */
  3822. }, {
  3823. key: "offAnyOutgoing",
  3824. value: function offAnyOutgoing(listener) {
  3825. if (!this._anyOutgoingListeners) {
  3826. return this;
  3827. }
  3828. if (listener) {
  3829. var listeners = this._anyOutgoingListeners;
  3830. for (var i = 0; i < listeners.length; i++) {
  3831. if (listener === listeners[i]) {
  3832. listeners.splice(i, 1);
  3833. return this;
  3834. }
  3835. }
  3836. } else {
  3837. this._anyOutgoingListeners = [];
  3838. }
  3839. return this;
  3840. }
  3841. /**
  3842. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  3843. * e.g. to remove listeners.
  3844. */
  3845. }, {
  3846. key: "listenersAnyOutgoing",
  3847. value: function listenersAnyOutgoing() {
  3848. return this._anyOutgoingListeners || [];
  3849. }
  3850. /**
  3851. * Notify the listeners for each packet sent
  3852. *
  3853. * @param packet
  3854. *
  3855. * @private
  3856. */
  3857. }, {
  3858. key: "notifyOutgoingListeners",
  3859. value: function notifyOutgoingListeners(packet) {
  3860. if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
  3861. var listeners = this._anyOutgoingListeners.slice();
  3862. var _iterator2 = _createForOfIteratorHelper(listeners),
  3863. _step2;
  3864. try {
  3865. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  3866. var listener = _step2.value;
  3867. listener.apply(this, packet.data);
  3868. }
  3869. } catch (err) {
  3870. _iterator2.e(err);
  3871. } finally {
  3872. _iterator2.f();
  3873. }
  3874. }
  3875. }
  3876. }]);
  3877. return Socket;
  3878. }(Emitter);
  3879. /**
  3880. * Initialize backoff timer with `opts`.
  3881. *
  3882. * - `min` initial timeout in milliseconds [100]
  3883. * - `max` max timeout [10000]
  3884. * - `jitter` [0]
  3885. * - `factor` [2]
  3886. *
  3887. * @param {Object} opts
  3888. * @api public
  3889. */
  3890. function Backoff(opts) {
  3891. opts = opts || {};
  3892. this.ms = opts.min || 100;
  3893. this.max = opts.max || 10000;
  3894. this.factor = opts.factor || 2;
  3895. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  3896. this.attempts = 0;
  3897. }
  3898. /**
  3899. * Return the backoff duration.
  3900. *
  3901. * @return {Number}
  3902. * @api public
  3903. */
  3904. Backoff.prototype.duration = function () {
  3905. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  3906. if (this.jitter) {
  3907. var rand = Math.random();
  3908. var deviation = Math.floor(rand * this.jitter * ms);
  3909. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  3910. }
  3911. return Math.min(ms, this.max) | 0;
  3912. };
  3913. /**
  3914. * Reset the number of attempts.
  3915. *
  3916. * @api public
  3917. */
  3918. Backoff.prototype.reset = function () {
  3919. this.attempts = 0;
  3920. };
  3921. /**
  3922. * Set the minimum duration
  3923. *
  3924. * @api public
  3925. */
  3926. Backoff.prototype.setMin = function (min) {
  3927. this.ms = min;
  3928. };
  3929. /**
  3930. * Set the maximum duration
  3931. *
  3932. * @api public
  3933. */
  3934. Backoff.prototype.setMax = function (max) {
  3935. this.max = max;
  3936. };
  3937. /**
  3938. * Set the jitter
  3939. *
  3940. * @api public
  3941. */
  3942. Backoff.prototype.setJitter = function (jitter) {
  3943. this.jitter = jitter;
  3944. };
  3945. var Manager = /*#__PURE__*/function (_Emitter) {
  3946. _inherits(Manager, _Emitter);
  3947. var _super = _createSuper(Manager);
  3948. function Manager(uri, opts) {
  3949. var _this;
  3950. _classCallCheck(this, Manager);
  3951. var _a;
  3952. _this = _super.call(this);
  3953. _this.nsps = {};
  3954. _this.subs = [];
  3955. if (uri && "object" === _typeof(uri)) {
  3956. opts = uri;
  3957. uri = undefined;
  3958. }
  3959. opts = opts || {};
  3960. opts.path = opts.path || "/socket.io";
  3961. _this.opts = opts;
  3962. installTimerFunctions(_assertThisInitialized(_this), opts);
  3963. _this.reconnection(opts.reconnection !== false);
  3964. _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  3965. _this.reconnectionDelay(opts.reconnectionDelay || 1000);
  3966. _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  3967. _this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
  3968. _this.backoff = new Backoff({
  3969. min: _this.reconnectionDelay(),
  3970. max: _this.reconnectionDelayMax(),
  3971. jitter: _this.randomizationFactor()
  3972. });
  3973. _this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  3974. _this._readyState = "closed";
  3975. _this.uri = uri;
  3976. var _parser = opts.parser || parser;
  3977. _this.encoder = new _parser.Encoder();
  3978. _this.decoder = new _parser.Decoder();
  3979. _this._autoConnect = opts.autoConnect !== false;
  3980. if (_this._autoConnect) _this.open();
  3981. return _this;
  3982. }
  3983. _createClass(Manager, [{
  3984. key: "reconnection",
  3985. value: function reconnection(v) {
  3986. if (!arguments.length) return this._reconnection;
  3987. this._reconnection = !!v;
  3988. return this;
  3989. }
  3990. }, {
  3991. key: "reconnectionAttempts",
  3992. value: function reconnectionAttempts(v) {
  3993. if (v === undefined) return this._reconnectionAttempts;
  3994. this._reconnectionAttempts = v;
  3995. return this;
  3996. }
  3997. }, {
  3998. key: "reconnectionDelay",
  3999. value: function reconnectionDelay(v) {
  4000. var _a;
  4001. if (v === undefined) return this._reconnectionDelay;
  4002. this._reconnectionDelay = v;
  4003. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
  4004. return this;
  4005. }
  4006. }, {
  4007. key: "randomizationFactor",
  4008. value: function randomizationFactor(v) {
  4009. var _a;
  4010. if (v === undefined) return this._randomizationFactor;
  4011. this._randomizationFactor = v;
  4012. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
  4013. return this;
  4014. }
  4015. }, {
  4016. key: "reconnectionDelayMax",
  4017. value: function reconnectionDelayMax(v) {
  4018. var _a;
  4019. if (v === undefined) return this._reconnectionDelayMax;
  4020. this._reconnectionDelayMax = v;
  4021. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
  4022. return this;
  4023. }
  4024. }, {
  4025. key: "timeout",
  4026. value: function timeout(v) {
  4027. if (!arguments.length) return this._timeout;
  4028. this._timeout = v;
  4029. return this;
  4030. }
  4031. /**
  4032. * Starts trying to reconnect if reconnection is enabled and we have not
  4033. * started reconnecting yet
  4034. *
  4035. * @private
  4036. */
  4037. }, {
  4038. key: "maybeReconnectOnOpen",
  4039. value: function maybeReconnectOnOpen() {
  4040. // Only try to reconnect if it's the first time we're connecting
  4041. if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
  4042. // keeps reconnection from firing twice for the same reconnection loop
  4043. this.reconnect();
  4044. }
  4045. }
  4046. /**
  4047. * Sets the current transport `socket`.
  4048. *
  4049. * @param {Function} fn - optional, callback
  4050. * @return self
  4051. * @public
  4052. */
  4053. }, {
  4054. key: "open",
  4055. value: function open(fn) {
  4056. var _this2 = this;
  4057. if (~this._readyState.indexOf("open")) return this;
  4058. this.engine = new Socket$1(this.uri, this.opts);
  4059. var socket = this.engine;
  4060. var self = this;
  4061. this._readyState = "opening";
  4062. this.skipReconnect = false;
  4063. // emit `open`
  4064. var openSubDestroy = on(socket, "open", function () {
  4065. self.onopen();
  4066. fn && fn();
  4067. });
  4068. var onError = function onError(err) {
  4069. _this2.cleanup();
  4070. _this2._readyState = "closed";
  4071. _this2.emitReserved("error", err);
  4072. if (fn) {
  4073. fn(err);
  4074. } else {
  4075. // Only do this if there is no fn to handle the error
  4076. _this2.maybeReconnectOnOpen();
  4077. }
  4078. };
  4079. // emit `error`
  4080. var errorSub = on(socket, "error", onError);
  4081. if (false !== this._timeout) {
  4082. var timeout = this._timeout;
  4083. // set timer
  4084. var timer = this.setTimeoutFn(function () {
  4085. openSubDestroy();
  4086. onError(new Error("timeout"));
  4087. socket.close();
  4088. }, timeout);
  4089. if (this.opts.autoUnref) {
  4090. timer.unref();
  4091. }
  4092. this.subs.push(function () {
  4093. _this2.clearTimeoutFn(timer);
  4094. });
  4095. }
  4096. this.subs.push(openSubDestroy);
  4097. this.subs.push(errorSub);
  4098. return this;
  4099. }
  4100. /**
  4101. * Alias for open()
  4102. *
  4103. * @return self
  4104. * @public
  4105. */
  4106. }, {
  4107. key: "connect",
  4108. value: function connect(fn) {
  4109. return this.open(fn);
  4110. }
  4111. /**
  4112. * Called upon transport open.
  4113. *
  4114. * @private
  4115. */
  4116. }, {
  4117. key: "onopen",
  4118. value: function onopen() {
  4119. // clear old subs
  4120. this.cleanup();
  4121. // mark as open
  4122. this._readyState = "open";
  4123. this.emitReserved("open");
  4124. // add new subs
  4125. var socket = this.engine;
  4126. 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)));
  4127. }
  4128. /**
  4129. * Called upon a ping.
  4130. *
  4131. * @private
  4132. */
  4133. }, {
  4134. key: "onping",
  4135. value: function onping() {
  4136. this.emitReserved("ping");
  4137. }
  4138. /**
  4139. * Called with data.
  4140. *
  4141. * @private
  4142. */
  4143. }, {
  4144. key: "ondata",
  4145. value: function ondata(data) {
  4146. try {
  4147. this.decoder.add(data);
  4148. } catch (e) {
  4149. this.onclose("parse error", e);
  4150. }
  4151. }
  4152. /**
  4153. * Called when parser fully decodes a packet.
  4154. *
  4155. * @private
  4156. */
  4157. }, {
  4158. key: "ondecoded",
  4159. value: function ondecoded(packet) {
  4160. var _this3 = this;
  4161. // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
  4162. nextTick(function () {
  4163. _this3.emitReserved("packet", packet);
  4164. }, this.setTimeoutFn);
  4165. }
  4166. /**
  4167. * Called upon socket error.
  4168. *
  4169. * @private
  4170. */
  4171. }, {
  4172. key: "onerror",
  4173. value: function onerror(err) {
  4174. this.emitReserved("error", err);
  4175. }
  4176. /**
  4177. * Creates a new socket for the given `nsp`.
  4178. *
  4179. * @return {Socket}
  4180. * @public
  4181. */
  4182. }, {
  4183. key: "socket",
  4184. value: function socket(nsp, opts) {
  4185. var socket = this.nsps[nsp];
  4186. if (!socket) {
  4187. socket = new Socket(this, nsp, opts);
  4188. this.nsps[nsp] = socket;
  4189. } else if (this._autoConnect && !socket.active) {
  4190. socket.connect();
  4191. }
  4192. return socket;
  4193. }
  4194. /**
  4195. * Called upon a socket close.
  4196. *
  4197. * @param socket
  4198. * @private
  4199. */
  4200. }, {
  4201. key: "_destroy",
  4202. value: function _destroy(socket) {
  4203. var nsps = Object.keys(this.nsps);
  4204. for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) {
  4205. var nsp = _nsps[_i];
  4206. var _socket = this.nsps[nsp];
  4207. if (_socket.active) {
  4208. return;
  4209. }
  4210. }
  4211. this._close();
  4212. }
  4213. /**
  4214. * Writes a packet.
  4215. *
  4216. * @param packet
  4217. * @private
  4218. */
  4219. }, {
  4220. key: "_packet",
  4221. value: function _packet(packet) {
  4222. var encodedPackets = this.encoder.encode(packet);
  4223. for (var i = 0; i < encodedPackets.length; i++) {
  4224. this.engine.write(encodedPackets[i], packet.options);
  4225. }
  4226. }
  4227. /**
  4228. * Clean up transport subscriptions and packet buffer.
  4229. *
  4230. * @private
  4231. */
  4232. }, {
  4233. key: "cleanup",
  4234. value: function cleanup() {
  4235. this.subs.forEach(function (subDestroy) {
  4236. return subDestroy();
  4237. });
  4238. this.subs.length = 0;
  4239. this.decoder.destroy();
  4240. }
  4241. /**
  4242. * Close the current socket.
  4243. *
  4244. * @private
  4245. */
  4246. }, {
  4247. key: "_close",
  4248. value: function _close() {
  4249. this.skipReconnect = true;
  4250. this._reconnecting = false;
  4251. this.onclose("forced close");
  4252. if (this.engine) this.engine.close();
  4253. }
  4254. /**
  4255. * Alias for close()
  4256. *
  4257. * @private
  4258. */
  4259. }, {
  4260. key: "disconnect",
  4261. value: function disconnect() {
  4262. return this._close();
  4263. }
  4264. /**
  4265. * Called upon engine close.
  4266. *
  4267. * @private
  4268. */
  4269. }, {
  4270. key: "onclose",
  4271. value: function onclose(reason, description) {
  4272. this.cleanup();
  4273. this.backoff.reset();
  4274. this._readyState = "closed";
  4275. this.emitReserved("close", reason, description);
  4276. if (this._reconnection && !this.skipReconnect) {
  4277. this.reconnect();
  4278. }
  4279. }
  4280. /**
  4281. * Attempt a reconnection.
  4282. *
  4283. * @private
  4284. */
  4285. }, {
  4286. key: "reconnect",
  4287. value: function reconnect() {
  4288. var _this4 = this;
  4289. if (this._reconnecting || this.skipReconnect) return this;
  4290. var self = this;
  4291. if (this.backoff.attempts >= this._reconnectionAttempts) {
  4292. this.backoff.reset();
  4293. this.emitReserved("reconnect_failed");
  4294. this._reconnecting = false;
  4295. } else {
  4296. var delay = this.backoff.duration();
  4297. this._reconnecting = true;
  4298. var timer = this.setTimeoutFn(function () {
  4299. if (self.skipReconnect) return;
  4300. _this4.emitReserved("reconnect_attempt", self.backoff.attempts);
  4301. // check again for the case socket closed in above events
  4302. if (self.skipReconnect) return;
  4303. self.open(function (err) {
  4304. if (err) {
  4305. self._reconnecting = false;
  4306. self.reconnect();
  4307. _this4.emitReserved("reconnect_error", err);
  4308. } else {
  4309. self.onreconnect();
  4310. }
  4311. });
  4312. }, delay);
  4313. if (this.opts.autoUnref) {
  4314. timer.unref();
  4315. }
  4316. this.subs.push(function () {
  4317. _this4.clearTimeoutFn(timer);
  4318. });
  4319. }
  4320. }
  4321. /**
  4322. * Called upon successful reconnect.
  4323. *
  4324. * @private
  4325. */
  4326. }, {
  4327. key: "onreconnect",
  4328. value: function onreconnect() {
  4329. var attempt = this.backoff.attempts;
  4330. this._reconnecting = false;
  4331. this.backoff.reset();
  4332. this.emitReserved("reconnect", attempt);
  4333. }
  4334. }]);
  4335. return Manager;
  4336. }(Emitter);
  4337. /**
  4338. * Managers cache.
  4339. */
  4340. var cache = {};
  4341. function lookup(uri, opts) {
  4342. if (_typeof(uri) === "object") {
  4343. opts = uri;
  4344. uri = undefined;
  4345. }
  4346. opts = opts || {};
  4347. var parsed = url(uri, opts.path || "/socket.io");
  4348. var source = parsed.source;
  4349. var id = parsed.id;
  4350. var path = parsed.path;
  4351. var sameNamespace = cache[id] && path in cache[id]["nsps"];
  4352. var newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
  4353. var io;
  4354. if (newConnection) {
  4355. io = new Manager(source, opts);
  4356. } else {
  4357. if (!cache[id]) {
  4358. cache[id] = new Manager(source, opts);
  4359. }
  4360. io = cache[id];
  4361. }
  4362. if (parsed.query && !opts.query) {
  4363. opts.query = parsed.queryKey;
  4364. }
  4365. return io.socket(parsed.path, opts);
  4366. }
  4367. // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
  4368. // namespace (e.g. `io.connect(...)`), for backward compatibility
  4369. _extends(lookup, {
  4370. Manager: Manager,
  4371. Socket: Socket,
  4372. io: lookup,
  4373. connect: lookup
  4374. });
  4375. return lookup;
  4376. }));
  4377. //# sourceMappingURL=socket.io.js.map